如何停止START_STICKY服务的Android方法

4

我的应用程序使用第三方库,而该库会启动一个START_STICKY服务。因此,即使应用程序被销毁并且服务被杀死,它也会自动重新启动。

我的问题是,是否有任何方法可以将此服务的生命周期更改为与应用程序相同?当应用程序启动时启动服务,当应用程序停止时停止服务。

2个回答

2
在清单文件中为该服务添加一个“意图过滤器”。
 <service
        android:name="ServiceName"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="IntentName"/>
        </intent-filter>
    </service>

然后使用此意图在任何您想要的地方启动或停止服务。
String intentName="IntentName";
Intent i=new Intent(itentName);
context.stopService(i);

或者

context.startService(i);

0

我认为你有两个选项:

  • 你是否可以访问它的服务意图?如果是这种情况,您可以调用stopService(theIntent)
  • 如果您可以访问服务实例,则可以执行stopSelf()

1
谢谢!我尝试在onDestroy中使用Intent intent = new Intent(this, Service.class),但服务仍然重新启动。我如何访问服务器实例? - lseeo
你的意思是调用 stopService(new Intent(yourContext, TheService.class)) 吗?如果是这样,那么我认为该库会重新启动它。你能提供更多关于该库的信息吗? - Guillermo Merino
2
你解决了这个问题吗?如果是,请写下结果或将此答案标记为好的;否则,请提供更多信息。 - Guillermo Merino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接