5
activityManager.getRunningServices(Integer.MAX_VALUE);

This method returns a list which includes service which is stopped manually.

Settings > Applications > Running services

Cœur
  • 37,241
  • 25
  • 195
  • 267
tumbudu
  • 699
  • 11
  • 26

1 Answers1

3

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.

//use this code to check your service is running or not

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;
}
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
  • ref: http://stackoverflow.com/questions/5446565/android-how-do-i-check-if-activity-is-running – Padma Kumar Jan 03 '12 at 10:42
  • 1
    that is what i did.. which is failing.. as manager.getRunningServices(Integer.MAX_VALUE) is returning service which is manually stopped... – tumbudu Jan 03 '12 at 12:32
  • is that your own service of system default service which you stopped. – Padma Kumar Jan 03 '12 at 12:47
  • can you send your apk so that I can check. – Padma Kumar Jan 05 '12 at 11:53
  • I observed that service is still running.. but it is not shown under running services in settings.... :-? http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/2.3_r1/com/android/settings/applications/RunningState.java#143 I can see if started flag is false and clientLable is =0 it is not shown in list if (!si.started && si.clientLabel == 0) { continue; } Is any callback which called when service is stopped using settings app? – tumbudu Jan 05 '12 at 12:03
  • 6
    Fixed this by adding hack... http://groups.google.com/group/android-developers/browse_thread/thread/c5f91f45cfa3e1cc?pli=1 if ( !serviceInfo.started && (serviceInfo.clientLabel == 0) ) { controller.stopService(MYSERVICE); return; } – tumbudu Jan 05 '12 at 13:50
  • Do not call "service.service.getClassName()" if your users may have several flavors of your application installed, which have the same service or this will return true, although your service is not running, but from another flavor – JacksOnF1re Aug 14 '17 at 14:37