user1166635
user1166635

Reputation: 2801

How to get reference to running service?

There is a one problem - my main activity starts the service and be closed then. When the application starts next time the application should get reference to this service and stop it. But I don't know how I can get a reference to a running service. Please, I hope you can help me. Thank you.

Upvotes: 12

Views: 6166

Answers (2)

malexmave
malexmave

Reputation: 1300

This answer is based on the answer by @DawidSajdak. His code is mostly correct, but he switched the return statements, so it gives the opposite of the intended result. The correct code should be:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("your.service.classname".equals(service.service.getClassName())) {
            return true; // Package name matches, our service is running
        }
    }
    return false; // No matching package name found => Our service is not running
}

if(isMyServiceRunning()) {
    stopService(new Intent(ServiceTest.this,MailService.class));
}

Upvotes: 10

Dawid Sajdak
Dawid Sajdak

Reputation: 3084

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("your.service.classname".equals(service.service.getClassName())) {
            return false;
        }
    }
    return true;
}

if(isMyServiceRunning()) {
    stopService(new Intent(ServiceTest.this,MailService.class));
}

Upvotes: -1

Related Questions