Android源碼解析-異步任務(wù)

android源碼解析-異步消息

android異步消息中我們常用的就是如下方式

先創(chuàng)建一個(gè)handler實(shí)例:

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //處理message返回結(jié)果
};

接著開(kāi)啟一個(gè)線程:

new Thread(new Runnable() {
        @Override
        public void run() {
        handler.sendEmptyMessage(2);
        }
    }).start();

我們執(zhí)行了handler.sendEmptyMessage();方法,但是在主線程接到了返回結(jié)果,下面我們來(lái)探究一下原因.

原因探究

我們先看Handler.class的構(gòu)造方法

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() ||klass.isLocalClass()) &&
            (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName());
            }
        }
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
            }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

構(gòu)造方法創(chuàng)建了Looper的實(shí)例和MessageQueue的引用對(duì)象.創(chuàng)建了Looper的實(shí)例也就找到了線程對(duì)應(yīng)的looper和MessageQueue,因?yàn)橐粋€(gè)MessageQueue對(duì)應(yīng)的只有一個(gè)Looper.中間有一句mLooper = Looper.myLooper(); 我們稍后再看.
接下來(lái)看Handler調(diào)用的sendMessage方法。你會(huì)發(fā)現(xiàn)所有的方法調(diào)用的都是sendMessageAtTime()方法,那我們就看一下sendMessageAtTime()方法吧:

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
                RuntimeException e = new RuntimeException(this + " sendMessageAtTime()called with no mQueue");
                Log.w("Looper", e.getMessage(), e);
                return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
}

Handler的sendMessageAtTime()調(diào)用了queue.enqueueMessage()方法也就是messageQueue的入隊(duì)方法。
我們看一下enqueueMessage:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

我們看到handler把自己的實(shí)例放進(jìn)了msg的target這個(gè)到后邊會(huì)用到,接下來(lái)看MessageQueue類的enqueueMessage()方法:

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
        }
        
        synchronized (this) {
                if (mQuitting) {
                    IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }
        
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                        }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }
        
        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
                nativeWake(mPtr);
            }
    }
    return true;
}

里邊的for循環(huán)就是把消息放到messagequeue里的方法,根據(jù)when時(shí)間順序.
至此handler就把sendmessage中的message發(fā)送到messagequeue中.其中判斷了之前我們定義到msg里的handler實(shí)例.
那么MessageQueue是在哪里維護(hù)的呢?
看上邊的Handler構(gòu)造方法我們發(fā)現(xiàn)mQueue = mLooper.mQueue;這個(gè)行代碼.
也就是說(shuō)MessageQueue是在Looper維護(hù)的.
首先看一下Looper.prepare()

private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
            }
        sThreadLocal.set(new Looper(quitAllowed));
}

再看一下構(gòu)造方法:

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}

實(shí)際上在子線程必須執(zhí)行Looper.prepare()是因?yàn)樾枰ㄟ^(guò)sThreadLocal.set(new Looper(quitAllowed));建立Lopper與sThreadLocal的關(guān)系.我們?cè)倩乜碒andler的構(gòu)造方法mLooper = Looper.myLooper(); 這個(gè)方法.

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

我們看到直接return了sThreadLocal.get() 這就說(shuō)明了為什么要執(zhí)行Looper.prepare(),因?yàn)樾枰冉⒑蛃ThreadLocal的關(guān)系.

接下來(lái)看 Looper.loop();方法是執(zhí)行從enqueueMessage取出消息.


public static void loop() {
    final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }
        final MessageQueue queue = me.mQueue;    // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        for (;;) {
            Message msg = queue.next(); // might block
                if (msg == null) {
                    // No message indicates that the message queue is quitting.
                        return;
                    }
                // This must be in a local variable, in case a UI event sets the logger
                Printer logging = me.mLogging;
                if (logging != null) {
                    logging.println(">>>>> Dispatching to " + msg.target + " " +                    msg.callback + ": " + msg.what);
                            }
                msg.target.dispatchMessage(msg);
                if (logging != null) {
                    logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
                    }
                // Make sure that during the course of dispatching the
                // identity of the thread wasn't corrupted.
                final long newIdent = Binder.clearCallingIdentity();
                if (ident != newIdent) {
                    Log.wtf(TAG, "Thread identity changed from 0x"+ Long.toHexString(ident) + " to 0x"+ Long.toHexString(newIdent) + " while dispatching to "+ msg.target.getClass().getName() + " "+ msg.callback + " what=" + msg.what);
                    }        msg.recycleUnchecked();
            }
    }

有一個(gè)死循環(huán)執(zhí)行queue.next()方法.如果有消息就繼續(xù)執(zhí)行.然后執(zhí)行消息分發(fā)msg.target.dispatchMessage(msg);,可以看到msg.target就是我們最開(kāi)始在enqueueMessage步驟把handler.如果沒(méi)消息就休息等待.

下面看一下dispatchMessage:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
            handleCallback(msg);
            } else {
            if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                            return;
                            }
                    }
                handleMessage(msg);
            }
    }

最后分發(fā)完方法后執(zhí)行了handleMessage回調(diào)方法.handleMessage方法我們?cè)偈煜げ贿^(guò)了.就是我們new Handler創(chuàng)建的回調(diào).

總結(jié)

Handler通過(guò)初始化創(chuàng)建了Looper和實(shí)例化了MessageQueue,Looper創(chuàng)建的時(shí)候需要先執(zhí)行Looper.propar(),通過(guò)handler構(gòu)造方法匹配了本地ThreadLocal和線程-Looper-MessageQueue三者的對(duì)應(yīng)關(guān)系.
handler通過(guò)sendMessage方法執(zhí)行MessageQueue的enqueueMessage()方法,實(shí)現(xiàn)了往MessageQueue插入消息.
Looper.loop()方法從MessageQueue中取出消息.由for循環(huán)執(zhí)行queue.next()方法,然后執(zhí)行Handler的消息分發(fā)msg.target.dispatchMessage(msg);,也就是我們new Handler的回調(diào)方法.

一些題外話

android中啟動(dòng)關(guān)于線程和線程間通信的方法有很多,萬(wàn)變不離其宗,這里就簡(jiǎn)單的講下:

1.關(guān)于Handler.post()
(1)Handler.post();,這個(gè)方法的常用場(chǎng)景是我們?cè)谧泳€程完成,子線程中,調(diào)用post()方法后可以再方法內(nèi)寫ui操作的東西,,切記不要在子線程實(shí)例化的Handler執(zhí)行post()再操作UI,舉個(gè)例子在其他子線程1實(shí)例化的Handler,在子線程2執(zhí)行post()操作ui,那么還會(huì)報(bào)錯(cuò)告訴你"工作線程不能操作UI"的錯(cuò)誤.
(2)這個(gè)方法的實(shí)現(xiàn)原理并不是新開(kāi)啟線程或者怎么樣,原理還是異步消息,把Handler封裝到Message里作為傳遞然后跨線程執(zhí)行.具體請(qǐng)看源碼,由于不太復(fù)雜們這里就不貼了.

2.關(guān)于HandlerThread

HandlerThread handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        Handler handler_thread = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //線程內(nèi)耗時(shí)操作
                return false;
            }
        });
        handler_thread.sendEmptyMessage();

源碼解析
(1)當(dāng)執(zhí)行handlerThread.start();方法時(shí)候,執(zhí)行了HandlerThreadrun()方法,里邊執(zhí)行了Looper.prepare();Looper.loop();,又是熟悉的配方.在這一步建立了Looper/MessageQueue/threadLocal之前的關(guān)系,并且執(zhí)行了Looper.loop()方法,線程處于阻塞狀態(tài)。當(dāng)我們發(fā)送一個(gè)消息的時(shí)候就會(huì)被執(zhí)行。

3.關(guān)于IntentService:
(1)繼承自Service,它可以理解為就是一個(gè)Service,只不過(guò)融合了HandlerThread。
(2)繼承IntentService創(chuàng)建自己的服務(wù)的時(shí)候會(huì)重寫onHandleIntent()方法,因?yàn)檫@個(gè)方法就是在IntentService源碼中Handler的handleMessage() 里實(shí)現(xiàn)的方法。
(3)源碼在onCreate()中實(shí)現(xiàn)了HandlerThread并且執(zhí)行了start方法,然后new了ServiceHandler對(duì)象。
(4)在onStart()中發(fā)送消息。
(5)在onStartCommand()中調(diào)用了onStart()方法。
(6)總結(jié):這樣整個(gè)過(guò)程就通了,onCreate()創(chuàng)建HandlerThread,每次啟動(dòng)服務(wù)都會(huì)調(diào)用onStartCommand()也就實(shí)現(xiàn)了發(fā)送消息。然后onHandleIntent()回調(diào)處理線程耗時(shí)操作。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,698評(píng)論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,202評(píng)論 3 426
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 177,742評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 63,580評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,297評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 55,688評(píng)論 1 327
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,693評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 42,875評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,438評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,183評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,384評(píng)論 1 372
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,931評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,612評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 35,022評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 36,297評(píng)論 1 292
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,093評(píng)論 3 397
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,330評(píng)論 2 377

推薦閱讀更多精彩內(nèi)容