android best way to prevent service being killed?

2019-04-17 17:28发布

问题:

aim developing a small app to get latest articles and showing them in notifications bar

i know its bad idea to set service foreground coz its killing battery and device ram

and as we know there is some apps killing all running services every x minutes such as advanced task killer and my service has killed too so aim not abel to get latest news until the user lunch the app again

I've googled it how to prevent my service being killed i couldn't found a good solution most of them are too old and the rest are useless

i really need an advice is there any way to prevent my service being killed without foreground ?

any help are very very very much appreciated

回答1:

What you could do is using an AlarmManager and schedule a PendingIntent that will periodically wakes up and execute your stuff, like described here.



回答2:

i know its bad idea to set service foreground coz its killing battery and device ram

Not really. If you make a foreground service, you are telling Android to prioritize it and make sure that your Service is among the last ones to be killed when memory is low.

If all you did was start a foreground service that did nothing, no extra CPU cycles would be used up, causing minimal battery loss.

Understandably, since the service is running, the app itself is running, which means some memory is used up.

However, this doesn't fall under killing battery and ram.

As for handling service deaths. Without making a service foreground, you lose the prioritization. Keep in mind though, that even a foreground service is subject to termination if Android needs to reclaim memory.

If a task killer killed your app, you can't do much, it was basically a force-close by the user. As it was mentioned in another answer, you can use AlarmManager to schedule repeating Intents. Arguably, that would use up more battery because you would be waking up the device for the BroadcastReceiver to execute.

However, if Android itself killed your service, if you return START_STICKY from onStartCommand() it will recreate your service once memory is again available.