IntentService源碼分析

來源:互聯網
上載者:User

  和HandlerThread一樣,IntentService也是Android替我們封裝的一個Helper類,用來簡化開發流程的。接下來分析源碼的時候

你就明白是怎麼回事了。IntentService是一個按需處理用Intent表示的非同步請求的基礎Service類,本質上還是Android Service。

用戶端通過Context#startService(Intent);這樣的代碼來發起一個請求。Service只在沒啟動的情況下啟動,並且在一個worker thread

中處理所有的非同步請求,當所有的請求處理完畢時IntentService會自動停止,所以你不需要顯式的stop它。關於用戶端代碼如何正確的

使用它,請參看官方文檔 https://developer.android.com/training/run-background-service/create-service.html。

  接著和以往一樣,我們先來看看關鍵字段和ctor:

    private volatile Looper mServiceLooper; // 這2者都是和HandlerThread關聯的,只是沒明白這裡為什麼需要volatile關鍵字    private volatile ServiceHandler mServiceHandler; // 看起來他們都只是在UI線程中被訪問了,似乎並沒有什麼並發問題。。。    private String mName;    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個類分別是

ServiceRecord和ActiveServices,這裡我們看下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中定義的模板方法,也即我們處理請求的邏輯發生的地方

  As promised, 最後讓我們看下stopServiceToken究竟做了什麼,代碼如下:

    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();            }            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相關的代碼都已經分析完畢了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.