What happens if a Android Service is started multiple times?
The Service will only run in one instance. However, everytime you start the service, the onStartCommand()
method is called.
This is documented here
Absolutely Correct.
Only one instance of Service is created for an application process.
And when you call StartService();
again, then only onStartCommand()
gets called and new Intent is passed to onStartCommand()
method.
Note: onCreate()
is not called again.
About calling bindService()
multiple times:
When you call bindService()
multiple times, then again only one instance is used for Service and Android Runtime returns same IBinder object to client.
Means, onBind()
is not called multiple times. And just cached IBinder object is returned.
Adding some more information to the above answers which may be helpful for others is that, startId
that the onStartCommand()
method receives is different for every startService()
call.
Also if we write in for loop as mentioned above, code written in onHandleIntent()
would execute so many times as defined by the for loop frequency, but in sequence and not in parallel.
The concept is IntentService
creates a work queue and each request to startService()
trigger onStartCommand()
which in turn stores the intent in work queue and then pass the intent one by one to onHandleIntent()
.