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.
     *
     * <p>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.
     *
     * <p>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 
     * <var>startId</var>.  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}. 
     * 
     * <p><em>Be careful about ordering of your calls to this function.</em>.
     * 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.</p>
     * 
     * @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。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容