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