DJafari
DJafari

Reputation: 13545

check service is running or not

I Have a service that when i start it, schedule with alarm manager to run on 00:00, i want check that my service is running or not ?

when i check in Settings -> Applications -> Running Tasks, My Service Exist In Cached Process so below code is not working, because my service noting in running service, can any one help to me ?

private boolean isServiceRunning(String serviceName) {
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
        Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) i.next();
            if( runningServiceInfo.service.getClassName().equals(serviceName) ) {
                return true;
            }
        }
        return false;
    }

Upvotes: 4

Views: 883

Answers (2)

Pratik Butani
Pratik Butani

Reputation: 62419

I use following from inside an activity:

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;
}

Upvotes: 1

fedepaol
fedepaol

Reputation: 6862

BindService returns false if you don't have success in bind to the service:

Returns

If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.

I would use that to check if the service is not running.

Just be sure to not bind with AUTO_CREATE flag, or the service will be created as well.

Upvotes: 2

Related Questions