What happens if the Android service is launched several times?

If I have the following code:

Intent intent = new Intent(this,DownloadService.class); for(int i=0;i<filesArray.length;i++){ startService(intent); } 

In this code, the DownloadService continues with the IntentService .

So, now when I call startService(intent) , it means that I start a new service every time startService(intent) is called, or it means that DownloadService starts once, and then every time I call startService(intent) it will just be different from another using startId.

Does this make sense, and which one is the case?

+108
android
Nov 05 '11 at 11:32
source share
4 answers

The service will work only in one instance. However, each time the service starts, the onStartCommand() method is onStartCommand() .

It is described here.

+156
Nov 05 '11 at 11:37
source share

Absolutely correct. Only one service instance is created for the application process. And when you call onStart (); again, then only onStartCommand () is called and the new Intent is passed to the onStartCommand () method.

Note. onCreate () is not called again.

About calling bindService () several times:

When you call bindService () several times, then only one instance is used for the service again, and Runtime for Android runtime returns the same IBinder object to the client.

So onBind () is not called multiple times. And only the cached IBinder object is returned.

+16
Jun 30 '16 at 0:45
source share

Adding more of some of the information of the above answers, which may be useful to others, is that, the startId that the onStartCommand() method gets is different for each startService() call.

Also, if we write a for loop, as mentioned above, the code written in onHandleIntent() will execute as many times as determined by the frequency of the for loop, but sequentially rather than in parallel.

The idea is that the IntentService creates a work queue, and each request to startService() calls onStartCommand() which, in turn, stores the intention in the work queue, and then passes it in turn to onHandleIntent() .

+5
Jul 07 '16 at 17:18
source share

According to the document :

The startService () method returns immediately, and the Android system calls the onStartCommand () method of the service. If the service is not already running, the system first calls onCreate () and then calls onStartCommand ().

as well as

Multiple service start requests result in several corresponding calls to the onStartCommand () service. However, stopping it requires only one request to stop the service (using stopSelf () or stopService ()).

+1
Jun 09 '19 at 5:46
source share



All Articles