Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a Android Service is started multiple times?

Tags:

android

People also ask

What happens if we start a service twice android?

If you call startService() multiple times, the service will be called with onStartCommand() multiple times, one per call to startService() . Whether it will "restart" will depend upon whether the service was still considered to be running from the previous startService() call.

What happens when you start a service in Android?

A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf() , or another component can stop it by calling stopService() .

How do you know if a service has stopped on Android?

The following steps can be used to check stop service with/without calling onDestroy() . onDestroy() called: Go to Settings -> Application -> Running Services -> Select and stop your service.


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


According to the doc:

The startService() method returns immediately, and the Android system calls the service's onStartCommand() method. If the service isn't already running, the system first calls onCreate(), and then it calls onStartCommand().

and

Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it.