In my project I am starting a service when a button is clicked. But I don't want to start that service again when that button is clicked unless the previous one is already stopped. So I need to check first whether the service is running or not. I used the following method
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
But its not working for me, it doesnt give any exception but always returns false. what should I do now?
I think the reason why your service is not listed in running services is the way you start your service. The following proposal is the same thread you took your method from.
You MUST call startService for your service to be properly registered and
passing BIND_AUTO_CREATE will not suffice.
Like the following:
Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);
Try this and see if it works for you too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With