How can I prevent my Android app/service from being "killed" from a task manager?

Don picture Don · May 7, 2010 · Viewed 38.7k times · Source

It is very important that my service stay running until someone with a password stops the service from my UI screen. My app runs great but it is designed to be turned on/off by parents (with a password) on their kids phones. I have managed to make everything work but the problem I'm having is that if the kid uses a task manager to kill my service then my app is useless. I would be grateful to anyone who knows a way to either

1) monitor the service and start it back up automatically if its "killed" or 2) prevent someone from being able to kill it except from the activity (administration screen) that launched the service. Or both?

I'm sorry if I'm not very clear in describing the problem, I'm a beginner. I've made great progress so far but I am stuck at this last hurdle.

Answer

Yury picture Yury · Jul 27, 2012

You can use API method: startForeground(). Here is the explanation of it:

A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

Here you can find an example how to use this.

As for the question, you cannot prevent a service from being killed. It can be killed by the system. Even system services can be killed. If this happens they are restarted. You may use the same approach.