IntentService源码阅读

照例来看一下IntentService的类说明

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#startService(Intent)} calls; the
 * service is started as needed, handles each Intent in turn using a worker
 * thread, and stops itself when it runs out of work.
 *
 * 

This "work queue processor" pattern is commonly used to offload tasks * from an application's main thread. The IntentService class exists to * simplify this pattern and take care of the mechanics. To use it, extend * IntentService and implement {@link #onHandleIntent(Intent)}. IntentService * will receive the Intents, launch a worker thread, and stop the service as * appropriate. * *

All requests are handled on a single worker thread -- they may take as * long as necessary (and will not block the application's main loop), but * only one request will be processed at a time. * *

*

Developer Guides

*

For a detailed discussion about how to create services, read the * Services developer guide.

*
* * @see android.os.AsyncTask */

IntentService是一个Service的子类,用于在需要的时候处理异步的请求,这些请求参数是通过Intent来传递的。客户端通过startService(Intent)来传递请求,IntentService会用一个工作线程轮流处理每个Intent,当所有的Intent都处理完成之后,它会自动停止自己。

所有的请求都会在一个单独的线程中处理,同一时间只能处理一个请求,意思是说所有的请求是按照一个一个地处理的,只有处理完了一个请求才会处理下一个请求。

接着来看成员变量

    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

保持了一个Looper和ServiceHandler的引用,Looper是Handler消息机制必不可少的对象。我们来看一下ServiceHandler。

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

ServiceHandler是一个Handler的子类,在handleMessage中调用了onHandleIntent方法,并且自动停止了Service。但是工作线程在哪里呢?Service是运行在主线程中的,耗时任务同样无法在Service中运行。我们来看剩下的代码。

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }

    /**
     * Sets intent redelivery preferences.  Usually called from the constructor
     * with your preferred semantics.
     *
     * 

If enabled is true, * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_REDELIVER_INTENT}, so if this process dies before * {@link #onHandleIntent(Intent)} returns, the process will be restarted * and the intent redelivered. If multiple Intents have been sent, only * the most recent one is guaranteed to be redelivered. * *

If enabled is false (the default), * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent * dies along with it. */ public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled; } @Override public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); } /** * You should not override this method for your IntentService. Instead, * override {@link #onHandleIntent}, which the system calls when the IntentService * receives a start request. * @see android.app.Service#onStartCommand */ @Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; } @Override public void onDestroy() { mServiceLooper.quit(); } /** * Unless you provide binding for your service, you don't need to implement this * method, because the default implementation returns null. * @see android.app.Service#onBind */ @Override public IBinder onBind(Intent intent) { return null; } /** * This method is invoked on the worker thread with a request to process. * Only one Intent is processed at a time, but the processing happens on a * worker thread that runs independently from other application logic. * So, if this code takes a long time, it will hold up other requests to * the same IntentService, but it will not hold up anything else. * When all requests have been handled, the IntentService stops itself, * so you should not call {@link #stopSelf}. * * @param intent The value passed to {@link * android.content.Context#startService(Intent)}. */ @WorkerThread protected abstract void onHandleIntent(Intent intent);

可以看到我们需要关注的是onCreate()、onStart()、onStartCommand()以及onDestroy()方法。
先来看onCreate()

    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

创建了一个HandlerThread,这应该就是处理任务的线程了。接着初始化了mServiceLooper,然后创建了mServiceHandler = new ServiceHandler(mServiceLooper)。这是不是很熟悉呢,我们在使用HandlerThread结合Handler的时候就是这么使用的。

onStart()

    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

onStart方法仅仅是将请求传递给mServiceHandler去处理而已。

onStartCommand

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

onStartCommand方法也仅仅是将任务交给onStart方法去调度。当任务通过Intent传递过来的时候,onStartCommand方法将任务直接传递给onStart方法,由onStart方法将消息传递给Handler去处理。因为只有一个Thread去处理任务,所以同时过来多个任务时,也只是一个个地去执行。

onDestroy

  @Override
  public void onDestroy() {    
    mServiceLooper.quit();
  }

在这里执行了Looper的退出方法,Looper退出了,Handler就不再处理消息,HandlerThread也会停止。

** 现在来所以下IntentService的大体流程**

首先我们会通过Intent将任务参数(比如说URL)打包,然后调用startService(Intent)来将参数传递到onStartCommand,接着onStartCommand将任务传递给onStart方法,由onStart方法使用Handler的消息机制,将任务即Intent传递给Handler去处理,由于该Handler是通过HandlerThread创建的,所以该Handler操作的代码是运行在HandlerThread中的,这样就实现了后台处理任务,并且不会阻塞UI线程。还要说一点的是,在任务执行完毕之后,IntentService会自动停止。

你可能感兴趣的:(IntentService源码阅读)