Check whether service running

Method found on stackoverflow┬ábut it doesn’t appear to be the best answer. After stopping a service, this method may still see it as running. This is presumably because android will clear it our in its own time.

The method I have used is to set a flag in preferences that says whether the service is started or stopped. This has the additional benefit that code can also be added into the service to stop itself if it sees the flag is set to indicate it should be stopped.

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

 

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *