How to check if a service is running or not in android?

In my project, I start the service when the button is clicked. But I do not want to start this service again when this button is pressed, if the previous one has not been stopped. Therefore, you first need to check if the service is working 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 it does not work for me, it gives no exception, but always returns false. What should I do now?

+5
source share
2 answers

I think the reason your service is not listed in running services is because you start your service. The next sentence is the same thread from which you took your method.

You MUST call startService for your service to be properly registered and
passing BIND_AUTO_CREATE will not suffice.

As below:

Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);

, .

+3

false, , , .

0

All Articles