Using an IntentService to do background work

  • Written by  Clive


Doing it on the quiet: how to use an IntentService

intentService iconYou should do time consuming work, like downloading files, on a separate thread.

This will free up the main thread so your user can carry on using the app.

IntentServices are the preferred way for doing long running background operations.

You can request an IntentService from any of your fragments or activities. The requests are queued and handled one-after-the-other. The IntentService stops once all the requests have been handled.

An IntentService in action

I’ll show you how to use an IntentService using a simple app.

Running the app displays a text view, a text field and a button. The user enters some text, presses the button and the IntentService starts.

The IntentService does some work and then broadcasts an intent and stops itself when it’s finished. The intent contains the result of the work.

The main activity receives the intent and processes it.

IntentService tutorial app screenshot

Enter a message and press the button. The work is done by an IntentService. When it’s finished, it broadcasts an intent which is received, processed and the result displayed

Let’s have a look how it’s done.

Constructing the IntentService

We create our IntentService class, MyIntentService which extends the IntentService class.

We include a default constructor. Here’s the code:

IntentService constructor

Extend IntentService and create a default constructor, passing the name parameter to the super class

Handling the Intent

You call startService() to start the IntentService, passing an intent as a parameter. The intent can contain data that needs to be processed. The onHandleIntent() method processes this intent.

Here’s the code for the onHandleIntent() method:

IntentService onHandleIntent method

onHandleIntent() runs on a worker thread

Any number of requests can be sent to the IntentService. Requests are queued and processed one at a time.

The IntentService stops itself once there are no more requests in the queue.

The work

The work could be downloading a file for example.

Here’s our work request that has been sent to our IntentService:

IntentService work request

Our work request

Once the IntentService receives the work request, onHandleIntent() starts to…well, handle the intent.

We get the entered message out of the intent and assign it to inputText. Then  the service sleeps for 3 seconds.

Next, we create an output string, outputText by appending the current time to our input message.

Once the work is finished

You can decide what happens on completion of each request.

Note that onHandleIntent() runs on the worker thread. It cannot communicate directly with the main thread.

You could send a notification if you wish. I’ll show you how to send a broadcast message.

The Broadcast

We’re going to broadcast the result of the work request. It will be received by any component that’s registered to receive it.

First we need to create an Intent to include our output text. We’ll send this intent in our broadcast.

IntentService sendBroadcast method

We create and send the broadcast when the requested work is finished. The IntentService stops if there are no more requests in the queue

Note the following:

  • broadcastIntent – the intent we’ll broadcast when the requested work is finished. We’ll put our output text into this intent
  • setAction() – this is the action that will be used in the intent filter. Only components that have registered a broadcast receiver with the same action in their intent filter, will be able to handle the intent that we broadcast
  • MainActivity.ResponseReceiver.LOCAL_ACTION – com.example.myintentserviceapp.intent_service.ALL_DONE (a constant that we declared in the ResponseReceiver). Best practice is to use the Java package naming convention. It should also be self-describing. I’ve used the package name with ALL_DONE appended to it. This is the action that needs to be matched in the receiver’s intent filter.
  • putExtra ()-we put the output text into the intent

Finally we get an instance of the local broadcast manager and broadcast the intent.

Any component within the app that has registered a receiver with the same action in its filter will be able to process this broadcast intent.

The LocalBroadcastManager

The local broadcast manager is part of the support library.

It’s used to broadcast and receive intents only within an app. These broadcasts cannot be broadcast outside of the app. Neither can these receivers receive broadcasts from outside the app.

To use the local broadcast manager, import its support class:

LocalBroadcastManager support library

Import the support LocalBroadcastManager

The manifest

Finally, you need to define the IntentService in the AndroidManifest.xml file:

Register IntentService in the AndroidManifest.xml file

Register the service in the manifest file

The MainActivity

The main activity has a text view, a text field and a button.

The user enters text in the text field and presses the button. This starts the IntentService.

The action starts with a button press

Here’s the code that is executed when the button is pressed:

IntentService startService() button

Get the input text and start the IntentService

Note the following:

  • inputText – we get the text entered by the user
  • inputIntent – we create a new intent. The parameters are:
    • MainActivity.this -  context
    • MyIntentService.class – the service that we want to start
  • putExtra() – we put the input text into the intent. These are the parameters:
    • MyIntentService.TEXT_INPUT – the key
    • inputText – the value
  • startService() – starts the service. The intent passed as a parameter identifies the service. Each time startService() is called, the request is queued and handled consecutively by onHandleIntent(). The service stops itself when there are no more requests

The receiver

We create an inner class for our broadcast receiver. It receives the broadcast message from the service.

Here’s the code:

IntentService Broadcast receiver

Our broadcast receiver

Note the following:

  • LOCAL_ACTION - com.example.myintentserviceapp.intent_service.ALL_DONE. We’ll use this in our intent filter as the action. Best practice is to use the Java package naming convention. It should also be self-describing. I’ve used the package name with ALL_DONE appended to it
  • onReceive() – called in the main thread when the receiver receives an intent broadcast. Its parameters are:
    • context
    • intent – the intent sent in the broadcast by the service when the requested work completed
  • outPutTextView – the text view where we will display the text returned by the service
  • outputText – we get the text out of the intent
  • setText() – we display the output text in the output text view

Register the receiver

To be able to receive the broadcasts from the service, we need to do two things:

  • register the receiver to handle the broadcasts
  • include a filter to select which broadcasts to receive

We register the receiver in the activity’s onResume() method.

Here’s our code:

Register broadcast receiver in onresume

We need to register our receiver

Note the following:

  • broadcastFilter – enables this receiver to receive broadcasts with the same action
  • receiver – we create a new broadcast receiver
  • LocalBroadcastManager – we get an instance of the local broadcast manager
  • registerReceiver() – we register the receiver, passing two parameters:
    • our response receiver
    • our intent filter

Unregister the receiver

Once we have finished using the receiver, we need to unregister it. This also removes the filter.

We unregister the broadcast receiver in the activity’s onPause() method.

Here’s the code:

Unregister broadcast receiver in onpause

Unregister the receiver

Note the following:

  • localBroadcastManager – we get an instance of the local broadcast manager
  • unregisterReceiver() – unregisters our response receiver

I hope that you have found this tutorial helpful.

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.