Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 362
Reyjohn Avatar asked May 30 '12 13:05

Reyjohn


1 Answers

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.

like image 166
Korhan Ozturk Avatar answered Oct 21 '22 06:10

Korhan Ozturk