11

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.

user1166635
  • 2,741
  • 6
  • 22
  • 32

2 Answers2

10

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));
}
Community
  • 1
  • 1
malexmave
  • 1,283
  • 2
  • 17
  • 37
-1
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));
}
Dawid Sajdak
  • 3,064
  • 2
  • 23
  • 37
  • but how can I stop the service using your example? – user1166635 May 07 '12 at 12:56
  • 4
    Uhm .. that's pretty superfluous. Just call `stopService` regardless of whether your `Service` is running or not - there's no harm if it isn't - `stopService` will just return `false`. – Jens May 07 '12 at 13:28
  • 6
    Your example is wrong. The return values need swapped. – nathansizemore Mar 21 '15 at 18:11
  • ActivityManager should be used for testing and debugging purposes only. (https://developer.android.com/reference/android/app/ActivityManager.html) – sergiomse Nov 16 '17 at 15:18