michael
michael

Reputation: 110520

How can I find out if my service has started

In my code, I start my service conditionally like this:

Intent intent = new Intent(context, MyService.class);
context.startService(intent);

Can u please tell me if it is possible to find out if I have started the SAME Service before so that I don't start my service TWICE?

Thank you.

Upvotes: 5

Views: 3369

Answers (2)

Carlos3dx
Carlos3dx

Reputation: 491

Check this:

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;}

@bigstones: I don't know how, but I have a service that it can be created how many times as you like (maybe because I create inside it various runnable objects).

Upvotes: 5

bigstones
bigstones

Reputation: 15257

a service won't be started two times if it's already running, in fact even if you call multiple times startService() you need only one stopService() to stop it.

see here and here.

Upvotes: 8

Related Questions