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.
This is an extract from Android docs:
Think of this hack as "pinging" the
Service
since we can broadcast syncronously we can broadcast and get a result -- synchronously -- on the UI thread.Service
Activity
I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod here
EDIT (for the record):
Here is the solution proposed by hackbod:
I use the following from inside an activity:
And I call it using:
This works reliably, because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices.
All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not. Please note the "killable" column in the lifecycle events table in the Android documentation.
Xamarin C# version:
For the use-case given here we may simply make use of the
stopService()
method's return value. It returnstrue
if there exists the specified service and it is killed. Else it returnsfalse
. So you may restart the service if the result isfalse
else it is assured that the current service has been stopped. :) It would be better if you have a look at this.Got it!
You MUST call
startService()
for your service to be properly registered and passingBIND_AUTO_CREATE
will not suffice.And now the ServiceTools class: