Tuesday, July 10, 2012

Android: check if a service is running ?


The App I am working on consists of a background service, which continuously posts and checks data and a couple of activities. In the activity I would like to give the user possibility to toggle the related service on and off. But how do I know if my service is currently running or not?

After checking different approaches I eventually got to the following compact and reliable solution. From inside an activity:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

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 you process or which of the mentioned callbacks are called or not. Please note the “killable” column in the lifecycle events table in Android documentation.

No comments:

Post a Comment