May 16, 2015

Snippet #2. Know if a service is running

The second snippet is… -drum roll- How to know if a service is running in Android!

Check this:

public boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) 
                            getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : 
        manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName()
            .equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}
  • serviceClass: The class name of the service that you want to check.

What does it returns?

true if the service is running, false if not.