IntentService and Service - Android


Context:
You need to consumer a resource (REST/Web Service, Download Service or any process for a long time) asynchronize over a thread different to the Main Thread and you would want to use IntentService in the solution.

Solution:
To consumer any resource in background using strategy asynchronize you have two main options:
To do it using Service or IntetService. There are some differents between that components.
Service works in the Main thread and it will cause ANR (Android not responding) after a few seconds.
IntentService is a Service with another background thread working separately to do something without interacting with the Main thread.
In other words, Service class uses the application's main thread, while IntentService creates a worker thread  and uses that thread to run the service. You don't need to stop the IntenteService, it is automatically stops itself when there is not a Intent in queue.

To use it, the receiver must be registered using
      LocalBroadcastManager.getInstance(aContext).registerReceiver(handler, receiveFilter);
Then, the sending code has merely to call
      LocalBroadcastManager.getInstance(aContext).sendBroadcast(sendableIntent);
In both cases the Context can be an Activity or Service.
References : Cookbook Android - Ian Darwin.

It's recommended to use LocalBroadcastManager and BroadcastReceiver to register you receiver and to send your broadcast Intents. Using this components you can improve security and efficiently issues.


Figure 1. Sequence diagram IntentService implemented.
  • The Activity use BroadcastReceiver to create ResponseReceiver.
  • The Activity use LocalBroadcastManager to register the ResponseReceiver created.
  • The Activity use IntentService to start the Service.
  • The IntentService executes onHandleIntent. Any recursive operation or a-synchronized process is execute here.
  • The IntentService use LocalBroadcastManager to notify any message to the queque.
  • The BroadcastReceiver use onReceive operation to update the Activity.
  • The Activity use LocalBroadcastManager to unregister the ResponseReceiver created.
Figure 2. Sequence diagram IntentService implemented.

Result:
I implemented a example using this concepts. The example is a App that created a Service using IntentService. This Service notify two kind of state; when the App start and finished the Service is started and completed. I also used a BroadcastNotifier class as manager operations on LocalBroadcastManager and BroadcastReceiver.
Figure 3. Example IntentService Android.

You can get the source code at my account github.



Thanks for your comment