简体   繁体   English

即使在Android中销毁活动后也需要运行服务

[英]Need to run a service even after the activity is destroyed in android

I have tried using START_STICKY on the onStartCommand() method of intent services, I have even tried changing the process name of the service on the manifest.xml file. 我曾尝试在意图服务的onStartCommand()方法上使用START_STICKY ,甚至尝试更改manifest.xml文件中服务的进程名称。 But none works. 但是没有办法。 Whenever I kill the app, the service also gets destroyed. 每当我杀死该应用程序时,该服务也会被销毁。 I want to design a service that gets triggered when the user starts the app for the first time and then keeps on running even after user kills the application. 我想设计一个服务,该服务在用户首次启动该应用程序时触发,然后即使用户终止该应用程序也可以继续运行。 Any help will be useful 任何帮助都会有用

Your service must be in the foreground to prevent the system from closing it. 您的服务必须位于前台,以防止系统关闭它。 See the startForeground method in the Service class. 请参阅Service类中的startForeground方法。

In service class implement on destroy method which will trigger a broadcast. 在服务类中实现销毁方法,它将触发广播。 In that broadcast receiver class implement on receive method. 在那个广播接收器类中实现接收方法。 So whenever service destroyed this broadcast receiver class will execute onreceive method. 因此,每当服务销毁时,此广播接收器类都将执行onreceive方法。 In that onreceive method start the service again. 在该onreceive方法中,再次启动服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM