简体   繁体   中英

how to keep my background service active when android system kills my app?

I have a background service which runs in background to track screen on and off events. its started as below :

Intent intentService = new Intent(context, UnlockdService.class);
context.startService(intentService);

And it is returning Service.START_REDELIVER_INTENT in the method onStartCommand. But still when android system kills app this thread dies as well.

How can I prevent it?

I think it's a better solution to have a BroadcastReceiver instead of a Service. In your onReceive, you could then start your service to do its work, and then the service could self terminate - maybe you could use an IntentService if your work is one shot.

If you still want a Service, you can make it less likely to be killed by having a permanent notification in the notification bar, but that can be bad from a user perspective. I strongly recommend going the broadcast receiver route.

解决方案非常简单:从onStartCommand()返回START_STICKY onStartCommand()完成工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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