Android Sample Intent Service


Example

Here is an example of an IntentService that pretends to load images in the background. All you need to do to implement an IntentService is to provide a constructor that calls the super(String) constructor, and you need to implement the onHandleIntent(Intent) method.

public class ImageLoaderIntentService extends IntentService {

    public static final String IMAGE_URL = "url";

    /**
     * Define a constructor and call the super(String) constructor, in order to name the worker
     * thread - this is important if you want to debug and know the name of the thread upon 
     * which this Service is operating its jobs.
     */
    public ImageLoaderIntentService() {
        super("Example");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // This is where you do all your logic - this code is executed on a background thread

        String imageUrl = intent.getStringExtra(IMAGE_URL);

        if (!TextUtils.isEmpty(imageUrl)) {
            Drawable image = HttpUtils.loadImage(imageUrl); // HttpUtils is made-up for the example
        }

        // Send your drawable back to the UI now, so that you can use it - there are many ways
        // to achieve this, but they are out of reach for this example
    }
}

In order to start an IntentService, you need to send an Intent to it. You can do so from an Activity, for an example. Of course, you're not limited to that. Here is an example of how you would summon your new Service from an Activity class.

Intent serviceIntent = new Intent(this, ImageLoaderIntentService.class); // you can use 'this' as the first parameter if your class is a Context (i.e. an Activity, another Service, etc.), otherwise, supply the context differently
serviceIntent.putExtra(IMAGE_URL, "http://www.example-site.org/some/path/to/an/image");
startService(serviceIntent); // if you are not using 'this' in the first line, you also have to put the call to the Context object before startService(Intent) here

The IntentService processes the data from its Intents sequentially, so that you can send multiple Intents without worrying whether they will collide with each other. Only one Intent at a time is processed, the rest go in a queue. When all the jobs are complete, the IntentService will shut itself down automatically.