Chapter 12. IntentService

In Chapter 11 we discussed how the Service lifecycle can handle asynchronous execution while increasing the process rank and avoiding termination of the background threads by the runtime. The Service, however, is not an asynchronous technique by itself, because it executes on the UI thread. This shortcoming is addressed in the IntentService, which extends the Service class. The IntentService has the properties of the Service lifecycle but also adds built-in task processing on a background thread.

Fundamentals

The IntentService executes tasks on a single background thread—i.e., all tasks are executed sequentially. Users of the IntentService trigger the asynchronous execution by passing an Intent with Context.startService. If the IntentService is running, the Intent is queued until the background thread is ready to process it. If the IntentService is not running, a new component lifecycle is initiated and finishes when there are no more Intents to process. Hence, the IntentService runs only while there are tasks to execute.

Like a task-controlled Service (Task-Controlled Service), an IntentService always has an active component, reducing the risk of terminating the task prematurely.

Note

The background task executor in the IntentService is a HandlerThread. Unlike the default executor in AsyncTask, the IntentService executor is per instance and not per application. So an application can have multiple IntentService instances, where every instance executes tasks ...

Get Efficient Android Threading now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.