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..?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With