Android: multiple intentservices or one intentservice with multiple intents?

Jon picture Jon · Jun 13, 2016 · Viewed 7.1k times · Source

I'm a little confused about intentService. The docs say that if you send an intentService multiple tasks (intents) then it will execute them one after the other on one separate thread. My question is - is it possible to have multiple intentService threads at the same time or not? How do you differentiate in the code between creating three different intents on the same intentService (the same thread), or three separate intentServices each with it's own thread and one intent each to execute?

In other words, when you perform the command startService(intent) are you putting the intent in a single queue or does it start a new queue every time?

Intent someIntent1 = new Intent(this, myIntentService.class);
Intent someIntent2 = new Intent(this, myIntentService.class);
Intent someIntent3 = new Intent(this, myIntentService.class);
startService(someIntent1);
startService(someIntent2);
startService(someIntent3);

Answer

Submersed picture Submersed · Jun 13, 2016

1) Is it possible to have multiple intentService threads at the same time or not?

No, each IntentService only has one HandlerThread that it uses to execute requests in the order that "startService" is called. Unless, for some reason you decide to spawn your own Thread/Threads in the IntentService, but that would likely defeat the purpose of using IntentService in the first place. Services of the same manifest declaration i.e. service name=".MyIntentService" (and this is the same for normal Services) run as a singleton within their process, so until the Service is killed the same Service will receive additional start requests.

2) How do you differentiate in the code between creating three different intents on the same IntentService?

To differentiate between requests, use the Intent system as it's intended! Provide different "Actions" for different jobs the service can carry out, and pass along any extras the IntentService needs to run correctly for that particular job as extras in the Intent object you're using to start the Service.