IntentService源码分析

概要介绍

和HandlerThread一样,IntentService也是Android替我们封装的一个Helper类,用来简化开发流程的。IntentService是一个按需处理用Intent表示的异步请求的基础Service类,本质上还是Service。客户端通过Context#startService(Intent);这样的代码来发起一个请求。Service只在没启动的情况下才启动,并且在一个worker thread
中处理所有的请求,当所有的请求处理完毕时IntentService会自动停止,所以你不需要显式的stop它。关于客户端代码如何正确的使用它,请参看官方文档。

源码分析

接着和以往一样,我们先来看看关键字段和ctor:

    private volatile Looper mServiceLooper; // 这2者都是和HandlerThread关联的,只是没明白这里为什么需要volatile关键字
    private volatile ServiceHandler mServiceHandler; // 看起来他们都只是在UI线程中被访问了,似乎没有什么并发问题。。。可能是为了更保险
    private String mName; // 这里的mName给创建HandlerThread时用的名字
    private boolean mRedelivery;

    /**
     * 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;
    }

接下来看点有意思的代码:

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

        @Override
        public void handleMessage(Message msg) { // 基于我们前面关于Handler的介绍,这些代码都很容易理解
            onHandleIntent((Intent)msg.obj); // 注意这个Template方法,这是我们的子类中真正处理请求的地方
            stopSelf(msg.arg1);              // 注意看这里调用的是带参数的stopSelf并不是无参版本的stopSelf(),
        }                                    // 这是因为IntentService并不是处理完一个请求就退出,而是所有请求。
    }

    /**
     * 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) { // 设置是否重新发送Intent,一般在ctor中设置 mRedelivery = enabled; // 具体内容请详细阅读方法的doc } @Override public void onCreate() { // 此方法只在第一次需要创建service的时候调用 // 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(); // 启动接下来处理客户端异步请求的HandlerThread mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); // 拿到与之关联的Handler,用来向它发送待处理的消息(即客户端请求) }

接下来看2个onStartXXX相关的方法:

    @Override
    public void onStart(Intent intent, int startId) { // 其所作的事情就是根据参数获得一个对应的Message,
        Message msg = mServiceHandler.obtainMessage(); // send一个Message而已,消息的处理会在ServiceHandler
        msg.arg1 = startId;                            // 的handleMessage方法中进行
        msg.obj = intent;                             // 稍后我们分析下这里的startId咋来的 
        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; // 根据mRedelivery返回不同的策略值
    }

这里我们解释下int startId的来历。首先我们说下这部分代码位于frameworks/base/services/java/com/android/server/am/这个目录,
它下面有很多对Android内部机制来说很重要的类(比如“很有名”的ANR dialog就在这里)。与startId相关的2个类分别是ServiceRecordActiveServices,这里我们看下ServiceRecord中与startId相关的代码,如下:

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

    public int getLastStartId() {
        return lastStartId;
    }

    public int makeNextStartId() { // 此方法的调用是在ActiveServices中
        lastStartId++;
        if (lastStartId < 1) { // 通过代码我们可以看到startId是从1开始的正整数,每次+1
            lastStartId = 1;   // 你可以理解成客户端请求的次数(即startService调用的次数)
        }
        return lastStartId;
    }

这一点代码就完全解释了我们一直以来的困惑,像我自己一直以来就不理解这里的startId是干嘛用的,咋来的。

接下来我们看一组stopXXX相关的方法:

    /**
     * Stop the service, if it was previously started.  This is the same as
     * calling {@link android.content.Context#stopService} for this particular service.
     *  
     * @see #stopSelfResult(int)
     */
    public final void stopSelf() { // 内部调用参数为-1的版本,此方法会停止service
        stopSelf(-1);
    }

    /**
     * Old version of {@link #stopSelfResult} that doesn't return a result.
     *  
     * @see #stopSelfResult
     */
    public final void stopSelf(int startId) { // 参数startId要么是-1要么是从1开始的正整数,只有它等于我们最后一次调用
        if (mActivityManager == null) {       // startService时,onStartCommand里传递进来的startId值时,
            return;                           // service才会停止,否则并不会停止service。service会在处理完
        }                                     // 所有的客户端请求后自动停止。比如客户端调用了10次startService来
        try {                                 // 发出多个请求,那么只有当这里的startId == 10的时候,service才会停止,
            mActivityManager.stopServiceToken(// 其onDestroy方法才会被调用。另外由于我们的请求总是串行处理的,所以永远不会
                    new ComponentName(this, mClassName), mToken, startId); // 出现先stopSelf(10)再stopSelf(9)这种情况。
        } catch (RemoteException ex) {
        }
    }
    
    /**
     * Stop the service if the most recent time it was started was 
     * startId.  This is the same as calling {@link 
     * android.content.Context#stopService} for this particular service but allows you to 
     * safely avoid stopping if there is a start request from a client that you 
     * haven't yet seen in {@link #onStart}. 
     * 
     * 

Be careful about ordering of your calls to this function.. * If you call this function with the most-recently received ID before * you have called it for previously received IDs, the service will be * immediately stopped anyway. If you may end up processing IDs out * of order (such as by dispatching them on separate threads), then you * are responsible for stopping them in the same order you received them.

* * @param startId The most recent start identifier received in {@link * #onStart}. * @return Returns true if the startId matches the last start request * and the service will be stopped, else false. * * @see #stopSelf() */ public final boolean stopSelfResult(int startId) { // 此方法基本同上,不赘述,后面我们刨根问底下stopServiceToken到底咋实现的, if (mActivityManager == null) { // 看看这里startId是-1和正整数到底有啥区别。 return false; } try { return mActivityManager.stopServiceToken( new ComponentName(this, mClassName), mToken, startId); } catch (RemoteException ex) { } return false; } @Override public void onDestroy() { // 处理完所有客户端请求,stop service的时候会被调到,退出looper。 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) { // 当你只是个started service的时候,默认实现就足够了。 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)}. */ protected abstract void onHandleIntent(Intent intent); // handleMessage中定义的模板方法,也即我们处理请求的逻辑发生的地方

从上面的代码我们看出,停止Service时都调用了这样的代码:
mActivityManager.stopServiceToken(new ComponentName(this, mClassName), mToken, startId);这里的mActivityManager相关的代码,可以参考ActivityManagerNative.java文件,另外这里实际上是利用了Android的Binder机制,通过IPC调到了system_service进程中的ActivityManagerService#stopServiceToken方法,代码如下:

    @Override
    public boolean stopServiceToken(ComponentName className, IBinder token, // ActivityManagerService.java中的方法
            int startId) {
        synchronized(this) {
            return mServices.stopServiceTokenLocked(className, token, startId);
        }
    }

    boolean stopServiceTokenLocked(ComponentName className, IBinder token, // ActiveServices.java中的方法
            int startId) {
        if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
                + " " + token + " startId=" + startId);
        ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
        if (r != null) {
            if (startId >= 0) { // 注意这个判断,和我们猜测的一样
                // Asked to only stop if done with all work.  Note that
                // to avoid leaks, we will take this as dropping all
                // start items up to and including this one.
                ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
                if (si != null) {
                    while (r.deliveredStarts.size() > 0) {
                        ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
                        cur.removeUriPermissionsLocked();
                        if (cur == si) {
                            break;
                        }
                    }
                }

                if (r.getLastStartId() != startId) { // 这句代码是所有疑惑的答案
                    return false; // 如果不是最后一个请求的startId,直接返回了,并没有往下面执行;
                }                 // 这也就解释了为啥非last startId不能让service停止的原因。

                if (r.deliveredStarts.size() > 0) {
                    Slog.w(TAG, "stopServiceToken startId " + startId
                            + " is last, but have " + r.deliveredStarts.size()
                            + " remaining args");
                }
            }

            synchronized (r.stats.getBatteryStats()) {
                r.stats.stopRunningLocked();
            }
            // 如果是-1,直接往下走,所以一次调用就能停止Service
            r.startRequested = false;
            if (r.tracker != null) {
                r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
                        SystemClock.uptimeMillis());
            }
            r.callStart = false;
            final long origId = Binder.clearCallingIdentity();
            bringDownServiceIfNeededLocked(r, false, false); // 真正让service停止的代码
            Binder.restoreCallingIdentity(origId);
            return true;
        }
        return false;
    }

至此IntentService相关的所有代码都已经分析完毕了,enjoy。。。

你可能感兴趣的:(IntentService源码分析)