handler流程

1、Loop.prepare():創(chuàng)建Loop對象,初始化Loop中的MessageQueue跟當前的Thread;

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));

}

2、Loop.loop():拿到當前線程Loop對象,在拿到Loop中的消息隊列,for循環(huán)輪詢遍歷消息隊列,不斷調(diào)用MessageQueue的next方法,取出消息;

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;

for (;;) {

????Message msg = queue.next(); // might block

????if (msg == null) {

????????// No message indicates that the message queue is quitting. return;

????}

????msg.target.dispatchMessage(msg);

}

3、創(chuàng)建handler對象:創(chuàng)建handler對象時,會拿到當前線程的Loop對象,除了Main線程,其他線程都得初始化Loop對象,否則會報錯。通過Loop對象,把handler跟所屬線程的消息隊列關(guān)聯(lián)起來;

public Handler(Callback callback, boolean async) {

? ??mQueue = mLooper.mQueue;

}

4、發(fā)送消息:實際上是把消息加到消息隊列中,但在這一步之前,會把handler對象賦值給msg的target屬性;

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {

????msg.target = this;

????if (mAsynchronous) {

????????msg.setAsynchronous(true);

????}

????return queue.enqueueMessage(msg, uptimeMillis);

}

5、接收消息:將消息加入到了消息隊列,通過Loop的輪詢,就能取出當前加入到消息隊列的消息。最終把消息分發(fā)給消息體的target屬性(調(diào)用了Handler的dispatchMessage方法),這個target實際上就是發(fā)出消息的handler對象;

public void dispatchMessage(Message msg) {

????if (msg.callback != null) {

????????handleCallback(msg);

????} else {

????????if (mCallback != null) {

????????????if (mCallback.handleMessage(msg)) {

????????????????return;

? ? ? ? ? ? }

????????}

????????handleMessage(msg);

????}

}

6、處理消息:最終來到了Handler的dispatchMessage方法,方法里會判斷callback對象是否為空,如果為空,就調(diào)用handleMessage方法,就是我們平時創(chuàng)建handler時重寫的handleMessage方法。

handleMessage(msg)

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

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

  • 【今天講故事】 使用思維導圖3年多 先后做了100多張圖 思維導圖給我?guī)硖嗟母淖?今天來說說我和它的故事 01...
    朱朱蝸牛閱讀 971評論 3 3
  • 陽陽的作業(yè)是聽寫詞語,我負責報聽寫。 前面的詞都寫得很順利,寫到“開墾”的“墾”字時,陽陽猶豫了,思考了一會寫了“...
    舒芯閱讀 299評論 0 0
  • 如果問我,這世界上溫暖人心的是什么,我現(xiàn)在肯定會毫不猶豫的告訴你,那是愛,唯有愛才能夠真正感動我們的心,唯有愛才能...
    旅途覺醒閱讀 350評論 0 0

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