Android: Check if service is running via. bindService Android: Check if service is running via. bindService android android

Android: Check if service is running via. bindService


I have the same issue; seems the best known solution is to create a public static boolean in WhateverService, set to true during onCreate (or onStartCommand, your choice) and false during onDestroy. You can then access it from any other class in the same apk. This may be racey though. There is no API within Android to check if a service is running (without side effects): See http://groups.google.com/group/android-developers/browse_thread/thread/8c4bd731681b8331/bf3ae8ef79cad75d

I suppose the race condition comes from the fact that the OS may kill a remote service (in another process) at any time. Checking a local service (same process), as suggested above, seems race-free to me -- if the OS kills the service, it kills whatever checked its status too.


Use a shared preference to save service running flag.

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    int res = super.onStartCommand(intent, flags, startId);    setRunning(true);    return res;}@Overridepublic void onDestroy() {    super.onDestroy();    setRunning(false);}private void setRunning(boolean running) {    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());    SharedPreferences.Editor editor = pref.edit();    editor.putBoolean(PREF_IS_RUNNING, running);    editor.apply();}public static boolean isRunning(Context ctx) {    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());    return pref.getBoolean(PREF_IS_RUNNING, false);}


Another method:

public static boolean isServiceRunning(Context ctx, String serviceClassName) {    ActivityManager manager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {        if (TrackingService.class.getName().equals(serviceClassName)) {            return true;        }    }    return false;}