What would be the best way to check if an Android Service is running? I am aware of the ActivityManager
API, but it seems like the use of the API is not advised for
Use a shared preference to save service running flag.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
setRunning(true);
return res;
}
@Override
public 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);
}