How do I check if a background service (on Android) is running?
I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.
How do I check if a background service (on Android) is running?
I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.
Below is an elegant hack that covers all the
Ifs
. This is for local services only.And then later on:
onDestroy
isn't always called in the service so this is useless!For example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9.
You can use this (I didn't try this yet, but I hope this works):
The startService method returns a ComponentName object if there is an already running service. If not, null will be returned.
See public abstract ComponentName startService (Intent service).
This is not like checking I think, because it's starting the service, so you can add
stopService(someIntent);
under the code.Again, another alternative that people might find cleaner if they use pending intents (for instance with the
AlarmManager
:Where
CODE
is a constant that you define privately in your class to identify the pending intents associated to your service.