A foreground service is started and immediately bound to. Is there a way to know whether the serivce has been stopped or is still running after an activity restart. The safe way would be to execute startService
anyway, but is there a cleaner one?
Asked
Active
Viewed 660 times
0
-
no, there is no other way – pskink Oct 22 '17 at 09:32
1 Answers
1
You can use this method from:
https://stackoverflow.com/a/6452570/5457878
To check if your service is still running. You can call this method in your onResume()
or onCreate()
, and if it is not running, I would restart it.
private boolean isServiceRunning(String serviceName){
boolean serviceRunning = false;
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 = i
.next();
if(runningServiceInfo.service.getClassName().equals(serviceName)){
serviceRunning = true;
if(runningServiceInfo.foreground)
{
//service run in foreground
}
}
}
return serviceRunning;
}

gi097
- 7,313
- 3
- 27
- 49