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.
Asked
Active
Viewed 5,845 times
2 Answers
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));
}
-
2this is just checking the service is running or not can I get the instance of the service – avez raj Apr 03 '18 at 07:38
-
@avezRaj I didn't try this, but I would assume that "service" will contain a reference to the service once the if condition is true. – malexmave Apr 03 '18 at 08:41
-
1service does not contain reference of Service object. it gives an error of incompatable types – avez raj Apr 03 '18 at 09:12
-
In that case, I don't know. – malexmave Apr 03 '18 at 09:13
-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
-
-
4Uhm .. 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
-
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