IntentService on Android– asynchronous background tasks made easy

I

IntentService on Android– asynchronous background tasks made easy.

Android services are the workhorses of the platform. They allow applications to run long running tasks and give functionality to outside applications. Unfortunately, since they run in the background and are not visually obvious to developers, they can be a source of major headaches. If you have seen an ANR (activity not responding) or have wondered why a service was running when it shouldn’t be, a poorly implemented service could be the issue.
ANR

The dreaded ANR

The error when activity not responding

Let’s take a look at two major errors services cause:

ANRs. These disrupt the user’s experience and gives the user an option to force close. This can lead to a user uninstalling your app or the background process being in a disrupted state. The reason for this is that services are launched from your calling thread– usually this is the UI thread.
Always running services. Although Android provides mechanisms for scheduling and stopping services, not all developers follow the guidelines. In fact, a lot of the examples I’ve seen don’t even mention stopping your service. This can lead to slower overall performance, user confusion, and battery drain.

I imagine the Android developers at Google saw that this was becoming an issue and introduced the IntentService class in Android 1.5. The IntentService class addresses the above issues and abstracts all of the management of threads and service stopping from the developer. It’s very easy and powerful way of offloading tasks from the application’s main thread.

To create an IntentService it is as simple as:

public class LongRunningService extends IntentService {

@Override
protected void onHandleIntent(Intent intent) {
//here is where your long running task goes
}
}

About the author

abhijit.kurlekar
By abhijit.kurlekar

Category