Reputation: 4940
Is there any simple way of determining whether or not a certain service is active? I do this
boolean serviceWorking = false;
@Override
public void onCreate() {
serviceWorking = true;
}
@Override
public void onDestroy() {
serviceWorking = false;
stopSelf(startId);
}
but it is not working.
Upvotes: 2
Views: 12191
Reputation: 973
Information about running services is provided by the Android operating system through ActivityManager#getRunningServices. All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not.
U can write a method like this in activity
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
call it using:
isMyServiceRunning(MyService.class)
Upvotes: 7
Reputation: 439
I refer to the following: Check if service is running on Android?
public class MyService extends Service
{
private boolean mRunning;
@Override
public void onCreate()
{
super.onCreate();
mRunning = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (!mRunning) {
mRunning = true;
// do something
}
return super.onStartCommand(intent, flags, startId);
}
}
Upvotes: 1