Java 如何停止我的服务?
另请参见编辑2(下文) 我扩展了NotificationListenerService并实现了它的几种方法,包括Java 如何停止我的服务?,java,android,android-service,Java,Android,Android Service,另请参见编辑2(下文) 我扩展了NotificationListenerService并实现了它的几种方法,包括onDestroy()方法(但不是onBind()或onStartCommand()方法,因为据我所知,我不需要它们)。但是,当我调用selfStop()时,不会调用ondestory() 我知道还有其他关于调用selfStop()的链接,但我还没有找到任何解决问题的方法 我的服务由系统使用android清单中的以下代码启动: <service android:name=".No
onDestroy()
方法(但不是onBind()
或onStartCommand()
方法,因为据我所知,我不需要它们)。但是,当我调用selfStop()
时,不会调用ondestory()
我知道还有其他关于调用selfStop()
的链接,但我还没有找到任何解决问题的方法
我的服务由系统使用android清单中的以下代码启动:
<service android:name=".NotificationListener"
android:label="@string/service_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
编辑2
如果我在销毁扩展NotificationListenerService
(见上文)的服务时遇到问题,那么创建第二个服务
(例如MirrorClass)来基本镜像NotificationListenerService
,是否明智?然后,我将从扩展NotificationListenerService
的实际服务中引用该类及其方法。据推测,这将更容易销毁
,因为我是启动它的人(不同于android系统本身启动/调用的扩展NotificationListenerService
的服务)
大概是这样的:
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\u NOT\u STICKY
标志尝试覆盖onStartCommand()
:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
创建一个为您完成所有工作的新服务,而不是在此扩展NotificationListenerService
的服务中完成工作。一旦你想做一些工作,你所要做的就是使用startService()
方法,你大概会发送一些extra
,其中包含发布的通知。
然后,使用stopSelf()
方法可以很容易地停止该服务(该服务为您工作,并且不扩展NotificationListenerService
)。
使用stopSelf()
方法停止NotificationListenerService
本身不起作用。Place命令
stopSelf();
到
创建一些变量来检查服务是否应该停止。我尝试了START\u NOT\u STICKY常量,但这似乎只在由于设备内存不足而终止服务时才有影响。。。当我调用stopSelf()时,它没有任何影响。不过还是要感谢你的想法。也许它能工作,但接收事件的频率很高,所以这项服务似乎一直在运行?如果对通知的每次更改都会再次触发此服务,为什么需要停止此服务?我只需要在收到通知时,我的服务(扩展NotificationListenerService)处于活动/活动状态。我不希望它一直运行……当我在设备上的“运行应用”中检查我的应用时,它的使用量超过100MB(比任何其他应用都多)。它应该可以停止我的服务/销毁它,并让它再次创建,一旦它收到一个来自android系统的呼叫(通知已收到),对吗?谢谢你的帮助,有什么进展吗?我也想要这个。你能发布你服务的代码吗?@eldjon我添加了我的代码
stopSelf();
public int onStartCommand(Intent intent, int flags, int startId) {