如何停止我的服务?

另请参阅编辑2(下面)

我扩展了NotificationListenerService并实现了它的几个方法,包括onDestroy()方法(但不是onBind()onStartCommand()方法,因为我不需要它们,据我所知)。 但是当我调用selfStop()时,没有调用onDestroy()

我知道有关于调用selfStop()其他链接,但我没有找到任何解决我的问题的方法。

我的服务是由系统使用android-manifest的以下代码启动的:

      

同样,当我尝试在onCreate()方法中调用stopSelf()时(如果满足某些条件),不调用onDestroy()方法……服务不会被销毁。

它一直在使用RAM(我知道它正在运行,因为我可以在设置 – >应用程序 – >运行(在我的智能手机上)下看到它)

有谁知道为什么stopSelf()可能没有被执行/运行? 我是否必须在onBind()方法中执行某些操作(例如,更改返回的常量)? 是否甚至可以停止extends NotificationListenerService service ,以便它在系统再次调用之前不运行? 我必须在调用stopSelf()之前调用stopSelf()吗? 如果是,那么使用哪个ContextServiceConnection

编辑1

这是我的代码:

 public class Core extends NotificationListenerService { @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.i("abc", "onCreateService"); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); //check main switch state: check = prefs.getBoolean("mainswitch", true); Toast.makeText(Core.this, Boolean.toString(check), Toast.LENGTH_SHORT).show(); Log.i("abc", Boolean.toString(check)); if(check == false){ stopSelf(); } } @Override public void onNotificationPosted(StatusBarNotification sbn){} @Override public void onNotificationRemoved(StatusBarNotification sbn){} @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Log.i("abc", "onDestroyService"); } } 

编辑2

如果我在销毁扩展NotificationListenerService服务时遇到问题(见上文),那么创建第二个基本上镜像NotificationListenerService service (例如MirrorClass)是否明智? 然后,我将从扩展NotificationListenerService的实际服务中引用该类及其方法。 据推测,这将更容易被destroy因为我是启动它的人(不像扩展NotificationListenerService的服务,由android系统本身启动/调用)

像这样的东西:

 public class Core extends NotificationListenerService { @Override public void onCreate() { // TODO Auto-generated method stub } @Override public void onNotificationPosted(StatusBarNotification sbn){ MirrorClass.mOnNotificationPosted(sbn) //This is the reference to the other class } @Override public void onNotificationRemoved(StatusBarNotification sbn){} 

我真的很感激这里的一些指导/帮助,它开始向我倾斜了,谢谢

尝试使用START_NOT_STICKY标志覆盖服务中的onStartCommand()

 @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_NOT_STICKY; } 

创建一个为您完成所有工作的新服务,而不是在扩展NotificationListenerService此服务中进行工作。 一旦你想做一些工作,你所做的只是使用startService()方法,并且可能你会发送一些包含已发布通知的intent extras 。 然后使用stopSelf()方法很容易停止该服务(为您工作并且不扩展NotificationListenerService )。 使用stopSelf()方法停止NotificationListenerService本身不起作用。

放置命令

 stopSelf(); 

 public int onStartCommand(Intent intent, int flags, int startId) { 

制作一些变量以检查是否应该停止服务。