3

I was wondering if a service (myService.class) can be created twice(or more) when using the same class. for example if the first initiation is on Application (which means it keeps running on the background) and the others happens on broadcast received

 startService(new Intent(this, myService.class));

or if the service is currently running then the others are not initialize..?

user_s
  • 1,058
  • 2
  • 12
  • 35

2 Answers2

4

as discussed here, Service has a single instance. and as it stated on the docs every call to startService makes corresponding instance of the service onStartCommand to be invoked. But doesnt create a new instance.

Community
  • 1
  • 1
Ofek Ron
  • 8,354
  • 13
  • 55
  • 103
  • So correct me if I'm wrong - if it is on different context it is possible, but if I use the same context(getApplicationContext() for example) then only one instance is created, right? – user_s May 31 '15 at 10:02
  • no, afaik this is per application - that is per package – Ofek Ron May 31 '15 at 18:01
0

I found a simple solution for this.

Whenever the startService() is called, onCreate() and onStartCommand() are also called. But the variables are still the same and are not initialized again.

So, to tackle this, create a private field like:

private var isRunning = false

or:

private boolean isRunning = false;

Then, in onCreate():

    if (!isRunning) {
        Log.i("ServiceStarter", "On start called")
        isRunning = true
        // do your work here
    }
Ayush Jain
  • 23
  • 4