IntentService 分析

IntentService 是Android为我们提供的一个类,继承Service类,

第一步,先来看看源码里面开头的注释:

 
  1. /**

  2. * IntentService is a base class for {@link Service}s that handle asynchronous

  3. * requests (expressed as {@link Intent}s) on demand. Clients send requests

  4. * through {@link android.content.Context#startService(Intent)} calls; the

  5. * service is started as needed, handles each Intent in turn using a worker

  6. * thread, and stops itself when it runs out of work.

  7. *

  8. * <p>This "work queue processor" pattern is commonly used to offload tasks

  9. * from an application's main thread. The IntentService class exists to

  10. * simplify this pattern and take care of the mechanics. To use it, extend

  11. * IntentService and implement {@link #onHandleIntent(Intent)}. IntentService

  12. * will receive the Intents, launch a worker thread, and stop the service as

  13. * appropriate.

  14. *

  15. * <p>All requests are handled on a single worker thread -- they may take as

  16. * long as necessary (and will not block the application's main loop), but

  17. * only one request will be processed at a time.

  18. */

由上至少可以知道两点:
1. IntentService 基于 类Service,用来处理异步请求。客户端可以通过startService(Intent)来发出请求,该Service会在需要的时候创建,通过使用一个工作线程来处理请求,当所有的请求都处理完以后自动关闭;
2. 所有请求都单独由一个工作线程进行处理。
 

第二步,我们看看IntentService的成员变量:

 
  1. private volatile Looper mServiceLooper;

  2. private volatile ServiceHandler mServiceHandler;

  3. private String mName;

  4. private boolean mRedelivery;

ServiceHandler是一个静态内部类,代码如下:

 
  1. private final class ServiceHandler extends Handler {

  2. public ServiceHandler(Looper looper) {

  3. super(looper);

  4. }

  5.  
  6. @Override

  7. public void handleMessage(Message msg) {

  8. onHandleIntent((Intent)msg.obj);

  9. stopSelf(msg.arg1);

  10. }

  11. }

在handleMessage(Message msg)方法里,会调用onHandleIntent(Intent intent)方法处理请求,这一步说明了我们在使用IntentService时为什么得重载onHandleIntent(Intent intent)方法并在其中实现我们自己的处理;
接着,在处理完请求后就会调用stopSelf(int startId)尝试停止自己,注意这里调用的是stopSelf(int startId),而不是sotpSelf(),实际上stopSelf也是调用stopSelf(int startId),只不过startId指定为-1,两者的区别在于stopSelf(int startId)会等所有请求处理完才停止,而stopSelf()是直接停止。

其中startId的解释如下:

// startId A unique integer representing this specific request to start

可以简单理解startId记录了该Service被启动的次数,从1开始计算,每启动一次自增1,从ServiceRecord中可以看出,如下:

 
  1. final class ServiceRecord extends Binder {

  2.  
  3.         ...

  4.  
  5.         private int lastStartId;     // identifier of most recent start request.

  6.  
  7.         ...

  8.  
  9.         public int getLastStartId() {

  10.             return lastStartId;

  11.         }

  12.  
  13.         public int makeNextStartId() {

  14.             lastStartId++;

  15.             if (lastStartId < 1) {

  16.                 lastStartId = 1;

  17.             }

  18.             return lastStartId;

  19.        }

  20.  
  21.         ...

  22. }

由于这其中涉及Serivce创建和启动的复杂过程,这里只是提一下,故本节不深入讨论

第三步,我们来看看几个回调方法,我们知道Service创建时回调方法的调用顺序为:onCreate -> onStartCommand -> onStart,因此我们先看onCreate(),实现如下:

 
  1. @Override

  2. public void onCreate() {

  3. // TODO: It would be nice to have an option to hold a partial wakelock

  4. // during processing, and to have a static startService(Context, Intent)

  5. // method that would launch the service & hand off a wakelock.

  6.  
  7. super.onCreate();

  8. HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");

  9. thread.start();

  10.  
  11. mServiceLooper = thread.getLooper();

  12. mServiceHandler = new ServiceHandler(mServiceLooper);

  13. }

主要步骤如下:
1. 创建线程HandlerThread并启动
2. 获取线程的Looper,赋值给mServiceLooper

3. 以该Looper对象做参数创建ServiceHandler

关于HandlerThread的分析可以参考:HandlerThread浅析

接着看onStartCommand()

 
  1. /**

  2.  * You should not override this method for your IntentService. Instead,

  3. * override {@link #onHandleIntent}, which the system calls when the IntentService

  4. * receives a start request.

  5. * @see android.app.Service#onStartCommand

  6. */

  7. @Override

  8. public int onStartCommand(Intent intent, int flags, int startId) {

  9. onStart(intent, startId);

  10. return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;

  11. }

这里说明了不应该重载该方法,可以看到在该方法实现只是简单地调用了onStart(),把startService(Intent intent)传递过来的intent以及对应的startId传递给了onStart(), onStart()方法的实现如下:

 
  1. @Override

  2. public void onStart(Intent intent, int startId) {

  3. Message msg = mServiceHandler.obtainMessage();

  4. msg.arg1 = startId;

  5. msg.obj = intent;

  6. mServiceHandler.sendMessage(msg);

  7. }

在onStart()方法里,获取和Servicehandler关联的Message对象msg,并把intent赋值给msg的obj,把startId赋值给msg.arg1,然后发送msg,该Message会被MessageQueue接收,然后mServiceLooper会从该队列中取出,交给ServiceHandler处理,这样在就会执行前面介绍ServiceHandler的handleMessage(Message msg)方法。

猜你喜欢

转载自blog.csdn.net/baidu_32472003/article/details/81193798