Android How to queue multiple intents on an IntentService

ilomambo picture ilomambo · Feb 12, 2013 · Viewed 8.5k times · Source

I am a little bit confused regarding the usage of IntentService.

  1. The documentation says that IntentService queues all intents sent to it and process them one at a time.
  2. I took a look at the code of IntentService and I saw that onStartCommand() receives the intent, calls onStart() which sends it as a message to the intents queue

I am pretty sure I read somwhere in the documentation that onStartCommand() is called by the system only once, if you issue twice a startService(), the second call will not result in onStartCommand() being called.
I might be wrong here, because I have been looking for this piece of documentation and I cannot seem to find it.
This contradicts the previous concept that says you can queue many intents in IntentService through onStartCommand().

So I need help here, how do I queue multiple intents on an IntentService?

I see only two options:

  • Just call everytime startService() with different intents

  • Call directly onStart() or onStartCommand() (bypassing startService())

Answer

Graham Borland picture Graham Borland · Feb 12, 2013

You send the Intent with Context.startService() and the Intent is picked up by your service in onHandleIntent().

The first time you call startService() will result in the service's onStartCommand() being invoked. Think of it as a constructor. Subsequent calls to startService() do not need to start the service again, since it's already running; they will just result in more calls to the service's onHandleIntent().