- What is an Android Service? / What Is an <tt>IntentService</tt>?
- When Should You Consider Using <tt>IntentService</tt>?
- A Simple <tt>IntentService</tt> Example
Shane Conder and Lauren Darcey are serving as the technical chairs of the Voices That Matter Android Developer's Conference, February 9-10, 2012, San Francisco, CA.
One of the most commonly employed mantras of the Android developer is to keep all slow, blocking operations off the main “UI” thread. You’ll see it all over the Android SDK documentation. You’ll see it on the developer forums and blog posts. You’ll hear it all the time in our Android development books and tutorials. But while it’s easy to say it, it’s not always easy for new developers to implement. This article will show you one of the easiest ways to offload processing from the main thread without a lot of hassle: by using the IntentService class (android.app.IntentService).
What Is an Android Service?
On the Android platform, a service is one of the fundamental building blocks of an Android application. It can be a background process or an interface for a remote object, called from within your application. In both cases, the service object extends the Service class (android.app.Service) from the Android SDK.
Services are similar to activities or full applications, but without user interfaces or input. They have their own lifecycle but run in the same process as the application they are associated with. They can run indefinitely, or simply when needed. Like applications, a Service can be killed by the Android operating system under low-memory conditions. Also like applications, a Service has a main thread that can block, requiring intensive processing to be offloaded to worker threads. Like activities, each service must be registered appropriately within the application’s Android Manifest file.
What Is an IntentService?
An IntentService is a simplified type of Android Service that is triggered using an Intent object. The IntentService class handles much of the Service implementation for you. Instead, you can focus on implementing a single method called onHandleIntent(), which processes the specific task that needs doing. It does this, though, already on a different thread from the main thread.
Here’s how it works: The IntentService receives a request via the Intent, which includes some information about the task to be completed. This task is then added to a queue, if necessary, and all tasks are completed sequentially and asynchronously. As a type of Service, the IntentService can manage its own threads and works in the background to complete each task. Results can be broadcast back to the application, if necessary.