Make an Intent which will start a service if provided as a parameter to start Service(). - Android android.os

Android examples for android.os:Messenger

Description

Make an Intent which will start a service if provided as a parameter to start Service().

Demo Code


//package com.java2s;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import android.os.Handler;

import android.os.Messenger;

public class Main {
    /**/*from   ww w .j a v a2s.  c o  m*/
     * The key used to store/retrieve a Messenger extra from a Bundle.
     */
    public static final String MESSENGER_KEY = "MESSENGER";

    /**
     * Make an Intent which will start a service if provided as a
     * parameter to startService().
     * 
     * @param context      The context of the calling component
     * @param service      The class of the service to be
     *                          started. (For example, ThreadPoolDownloadService.class) 
     * @param handler      The handler that the service should
     *                          use to return a result. 
     * @param uri      The web URL that the service should download
     * 
     * This method is an example of the Factory Method Pattern,
     * because it creates and returns a different Intent depending on
     * the parameters provided to it.
     * 
     * The Intent is used as the Command Request in the Command
     * Processor Pattern when it is passed to the
     * ThreadPoolDownloadService using startService().
     * 
     * The Handler is used as the Proxy, Future, and Servant in the
     * Active Object Pattern when it is passed a message, which serves
     * as the Active Object, and acts depending on what the message
     * contains.
     * 
     * The handler *must* be wrapped in a Messenger to allow it to
     * operate across process boundaries.
     */
    public static Intent makeMessengerIntent(Context context,
            Class<?> service, Handler handler, String uri) {
        Messenger messenger = new Messenger(handler);

        Intent intent = new Intent(context, service);
        intent.putExtra(MESSENGER_KEY, messenger);
        intent.setData(Uri.parse(uri));

        return intent;
    }
}

Related Tutorials