Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何停止NotificationListenerService?_Java_Android_Notifications_Listener - Fatal编程技术网

Java 如何停止NotificationListenerService?

Java 如何停止NotificationListenerService?,java,android,notifications,listener,Java,Android,Notifications,Listener,我已经编写了NotificationListenerService的子类,它在我的应用程序运行时在后台运行。但是,我希望允许用户关闭服务,以防他们想要节省电池。我实施这一点如下: MainActivity.java @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will

我已经编写了
NotificationListenerService
的子类,它在我的应用程序运行时在后台运行。但是,我希望允许用户关闭服务,以防他们想要节省电池。我实施这一点如下:

MainActivity.java

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case R.id.action_quit:
                Intent serviceStopIntent = new Intent(getResources().getString(R.string.communicator_intent));
                serviceStopIntent.putExtra("command", "shutdown");
                sendBroadcast(serviceStopIntent);

        }
ListingService.java

public class ListeningService extends NotificationListenerService {
      public void doStop() {
        Log.d(LOGTAG, "***** DEBUG_jwir3: Requesting stop of ListeningService");
        this.stopSelf();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mCommunicator);
        Log.d(LOGTAG, "***** DEBUG_jwir3: Destroying ListeningService");
        mMessageHandler.shutdown();
    }

    class ListeningCommunicator extends BroadcastReceiver {
        @Override
        public void onReceive(Context aContext, Intent aIntent) {
            Log.d(LOGTAG, "***** DEBUG_jwir3: Received command");
            if (aIntent.getStringExtra("command").equals("shutdown")) {
                Log.d(LOGTAG, "***** DEBUG_jwir3: Received shutdown command");
                ListeningService.this.doStop();
            }
        }
    }
}
(我已经简化了代码,但如果需要,我可以给出更多的示例)

我知道,
BroadcastReceiver
正在接收消息,我知道正在调用
doStop()
(由于日志消息),但是没有调用服务的
onDestroy()
。另外,我可以从
设置->应用->运行
中看出该服务仍在运行

我一直在研究这个问题,似乎(出于某种原因)
NotificationListenerService
没有响应
stopSelf()
stopService()
请求。我发现这里的公认答案建议将
NotificationListenerService
包装到另一个
服务中,然后根据需要停止/启动该服务。不过,这似乎没有什么帮助,因为
NotificationListenerService
仍需要以某种方式停止,而此包装服务也无法停止

似乎应该有一个比公认的答案更好的方法来做这件事,我想知道是否有人知道我会如何做