Reputation: 649
I'm making a service on Android where it will be installed on a phone/tablet. Many people can use that tablet but only selected ones should have right to close the service. How can I achieve this? I googled & found some options:
NEW OPTION:
I have another idea to make it work : I'm will make it system app so that it will warn user when he tries to stop it. For system apps, when user presses the "stop" button from settings, a warning message pops up :" Closing this app may lead to..(blah blah)....". Do you know which intent is thrown to pop up this message? I think I can use that intent here and disable the "OK" option in this message
.
Upvotes: 11
Views: 892
Reputation: 116
Are you permmited to disable settings?
If so, in your service you could monitorize the running threads and kill the ones that belong to settings (By package name) or just make the system return to the launcher, the user will never reach a context where is able to close processes.
This solution does not irradiate correctness (Google recommend not to do that), but it will prevent the user to even see the option, and for a local (not whole market) app it might be acceptable.
Anyway, if you are able to handle some loss of data (just for a few seconds), I would say you to use the RETURN_STICKY answer.
Upvotes: 3
Reputation: 12725
Preventing a service from closing is nearly impossible. However, you can make that your service restarts a soon as it got closed.
Use startForeground. As stated in the docs:
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.)
Return START_STICKY from your onStartCommand
to restart your service as soon as a user closes your service. In most cases, your service will be restarted in <5s, this however depends on how often your service gets killed successively.
These two methods will make your service nearly unkillable.
Upvotes: 6
Reputation: 104464
Even if the user couldn't stop the service, the phone could still get powered off, run out of battery, or lose network connectivity. It's even conceivable that Android could kill the service process if it ran low on resources. So the code should be prepared to for handling the potential data loss in those events.
I'm not certain how you detect when the service has been stopped, but there's always AlarmManager for periodic polling.
Upvotes: 6