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
仍需要以某种方式停止,而此包装服务也无法停止
似乎应该有一个比公认的答案更好的方法来做这件事,我想知道是否有人知道我会如何做