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線程中被訪問了,似乎沒有什么并發問題。。??赡苁菫榱烁kU
    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。。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容