Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 942
michael Avatar asked Dec 13 '22 15:12

michael


2 Answers

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.

like image 121
bigstones Avatar answered Jan 17 '23 02:01

bigstones


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).

like image 24
Carlos3dx Avatar answered Jan 17 '23 03:01

Carlos3dx