ThreadLocal、HandlerThread以及IntentService三者關(guān)系全面解析

Android SDK里面很多類名都起的讓人傻傻分不清楚,本篇文章就是從IntentService這個(gè)組件的生命周期出發(fā),深度剖析ThreadLocal、HandlerThread以及IntentService之間錯(cuò)綜復(fù)雜的關(guān)系。

首先了解概念

ThreadLocal:線程的本地變量。該變量不與其他線程共享,只能在本線程內(nèi)操作。

HandlerThread:一種經(jīng)過包裝的Thread。隨著該thread啟動(dòng),其內(nèi)部的Looper會(huì)自動(dòng)開始循環(huán)。

IntentService:一種經(jīng)過包裝的Service。該Service內(nèi)部會(huì)自動(dòng)開啟一個(gè)線程用來執(zhí)行任務(wù),并在任務(wù)結(jié)束后自動(dòng)結(jié)束。

敲黑板!記住結(jié)論:

  1. HandlerThread本質(zhì)上仍是一個(gè)Thread。
  2. IntentService本質(zhì)上仍是一個(gè)Service。

IntentService的生命周期

既然IntentService也是個(gè)Service,那么就從它的onCreate方法看起。

IntentService的onCreate方法.png

關(guān)注三個(gè)點(diǎn):

  1. 實(shí)例化了一個(gè)HandlerThread,并啟動(dòng)該線程。
  2. 獲取該HandlerThread中自帶的Looper對(duì)象。
  3. 將獲取到的Looper對(duì)象作為參數(shù)用來實(shí)例化ServiceHandler。
HandlerThread部分源碼.png

首先,通過閱讀HandlerThread的源碼,可以發(fā)現(xiàn)HandlerThread在run方法中會(huì)幫我們創(chuàng)建好一個(gè)Looper并讓該Looper執(zhí)行l(wèi)oop方法。在深入理解Handler、Looper與MessageQueue之間的關(guān)系一文中,我們詳細(xì)的描述了Handler、Looper以及MesageQueue三者之間的關(guān)系。Looper循環(huán)是Handler能在線程中運(yùn)行的前提條件。
所以我們可以理解為,IntentService的onCreate方法中所用到的HandlerThread,相當(dāng)于是為IntentService快速的構(gòu)建并啟動(dòng)了一個(gè)帶有Looper的工作線程。

Looper部分源碼.png
其次,Looper在其prepare方法中會(huì)通過ThreadLocal將自身與當(dāng)前線程進(jìn)行綁定。同樣的,在通過Looper.myLooper獲取當(dāng)前線程的Looper對(duì)象時(shí),也是通過ThreadLocal進(jìn)行獲取。

最后一點(diǎn),就是ServiceHandler。

ServiceHandler源碼.png

ServiceHandler的構(gòu)造函數(shù)沒什么好講的,和普通Handler一樣。重點(diǎn)在于其handleMessage方法。
handlerMessage方法用來處理由Looper循環(huán)MessageQueue所得到的Message。此處的代碼邏輯為,當(dāng)有Message發(fā)送來,則會(huì)調(diào)用onHandleIntent方法進(jìn)行處理,而這個(gè)onHandleIntent方法則正是我們使用IntentService時(shí)必須要實(shí)現(xiàn)的抽象方法。當(dāng)onHandleIntent方法執(zhí)行完,便會(huì)調(diào)用Service的stopSelf方法終止該IntentService,以此達(dá)到任務(wù)執(zhí)行完自動(dòng)結(jié)束的效果。

下面放上IntentService的完整代碼:

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

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

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

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

    /**
     * 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) {
        mRedelivery = enabled;
    }

    @Override
    public void onCreate() {
        // 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();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        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(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        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
    @Nullable
    public IBinder onBind(Intent intent) {
        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)}.
     *               This may be null if the service is being restarted after
     *               its process has gone away; see
     *               {@link android.app.Service#onStartCommand}
     *               for details.
     */
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}

最后結(jié)合代碼完整的梳理一遍IntentService的執(zhí)行過程:
首先IntentService執(zhí)行onCreate方法,該方法中會(huì)創(chuàng)建一個(gè)HandlerThread線程并實(shí)例化一個(gè)內(nèi)部類ServiceHandler。
隨后,onStartCommand方法會(huì)調(diào)用onStart方法,在onStart方法內(nèi)部,會(huì)構(gòu)造一個(gè)Message,然后用ServiceHandler來發(fā)送該Message。
再之后,ServiceHandler的handleMessage方法會(huì)對(duì)發(fā)來的Mesage進(jìn)行處理,具體的處理邏輯則是交給抽象方法onHandleIntent來完成,而這個(gè)方法正是使用者使用IntentService必須要實(shí)現(xiàn)的方法,使用者應(yīng)該將該Service要執(zhí)行的任務(wù)寫在該抽象方法的實(shí)現(xiàn)中。
在onHandleIntent方法完成后,便會(huì)執(zhí)行Service的stopSelf(int id)方法,來結(jié)束該IntentService。
最后,在IntentService的onDestroy方法里,通過執(zhí)行mServiceLooper的quit()方法,終止掉該Looper循環(huán),也順帶結(jié)束了該IntentService對(duì)應(yīng)的工作線程。

通過整體流程分析,我們可以發(fā)現(xiàn),IntentService為我們封裝好了工作線程的初始化、啟動(dòng)以及結(jié)束相關(guān)的代碼,使得開發(fā)者能專注于業(yè)務(wù)邏輯的編寫,減少了忘記結(jié)束Service所帶來的內(nèi)存泄漏的威脅。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容