Handler 深入淺出

本篇文章已授權(quán)微信公眾號(hào) guolin_blog (郭霖)獨(dú)家發(fā)布

Handler 組成部分

  • Message:消息對(duì)象

  • MessageQueue:消息隊(duì)列

  • Looper:消息輪詢器

Handler 工作原理

  • Message:用于記錄消息攜帶的信息

  • MessageQueue:存取 Message 的隊(duì)列集合

  • Looper:不斷獲取是否有新的 Message 需要執(zhí)行

Message 對(duì)象介紹

獲取 Message 對(duì)象的兩種方式

有什么不一樣箱蟆?接下來查看一下 Message.obtain 這個(gè)靜態(tài)方法做了什么操作

先翻譯一下 obtain 的方法的注釋文檔

Return a new Message instance from the global pool. Allows us to avoid allocating new objects in many cases.

從全局池返回一個(gè)新的消息實(shí)例。允許我們?cè)谠S多情況下避免分配新對(duì)象。

看到這里大家心里應(yīng)該有底了漫雕,就是在復(fù)用之前用過的 Message 對(duì)象快骗,這里實(shí)際上是用到了一種享元設(shè)計(jì)模式跟狱,這種設(shè)計(jì)模式最大的特點(diǎn)就是復(fù)用對(duì)象弥锄,避免重復(fù)創(chuàng)建導(dǎo)致的內(nèi)存浪費(fèi)

再介紹一下 Message 對(duì)象的一些特殊的屬性掉丽,待會(huì)我們會(huì)用得到

Handler.sendMessage 解析

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}

public final boolean sendEmptyMessage(int what) {
    return sendEmptyMessageDelayed(what, 0);
}

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageDelayed(msg, delayMillis);
}

public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
    Message msg = Message.obtain();
    msg.what = what;
    return sendMessageAtTime(msg, uptimeMillis);
}

public final boolean sendMessageDelayed(Message msg, long delayMillis) {
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

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

public final boolean sendMessageAtFrontOfQueue(Message msg) {
    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, 0);
}

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

簡(jiǎn)單過一遍吓肋,發(fā)現(xiàn)一個(gè)問題凳怨,sendXXX 這些方式最終還是會(huì)調(diào)用到 enqueueMessage 這個(gè)方法上來,所以讓我們重點(diǎn)看一下這個(gè)方法

就在剛剛給大家看了一下 Handler 的特殊屬性,target 其實(shí)就是一個(gè) Handler 類型的對(duì)象肤舞,現(xiàn)在給它賦值為當(dāng)前的 Handler 對(duì)象紫新,其實(shí)這樣我們已經(jīng)不難斷定,它最后肯定會(huì)這樣回調(diào) Handler 的 handleMessage 的方法了

msg.target.handleMessage(msg);

MessageQueue.enqueueMessage 解析

這里只是設(shè)想李剖,接下來繼續(xù)看 queue.enqueueMessage 的方法芒率,發(fā)現(xiàn)這里標(biāo)紅點(diǎn)不進(jìn)去,我們可以直接點(diǎn)擊 MessageQueue 對(duì)象進(jìn)去篙顺,由于 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;
}

這里我們先講一個(gè)細(xì)節(jié)的問題德玫,MessageQueue 類中的幾乎所有的方法里面都有 synchronized 關(guān)鍵字匪蟀,證明這個(gè)類已經(jīng)處理過線程安全的問題了

剛剛的源碼你只需要簡(jiǎn)單過一遍,接下來我們挑重點(diǎn)的講宰僧,如果對(duì)鏈表不熟悉的先去百度了解一下(簡(jiǎn)單點(diǎn)的來說就是對(duì)象自己嵌套自己)材彪,這里用的是單向鏈表,我已經(jīng)把注釋打上去了琴儿,要集中精力看

// 標(biāo)記這個(gè) Message 已經(jīng)被使用
msg.markInUse();
msg.when = when;

// mMessages 是一個(gè) Message 對(duì)象
Message p = mMessages;
boolean needWake;

// 如果這個(gè)是第一個(gè)消息段化,如果這個(gè)消息需要馬上執(zhí)行,如果這個(gè)消息執(zhí)行的時(shí)間要比之前的消息要提前的話
if (p == null || when == 0 || when < p.when) {

    // 把這個(gè) Message 對(duì)象放置在鏈表第一個(gè)位置
    msg.next = p;
    mMessages = msg;
    needWake = mBlocked;

} else {
    needWake = mBlocked && p.target == null && msg.isAsynchronous();

    // 這塊比較難理解了造成,要注意集中精力显熏,不要腦子被轉(zhuǎn)暈了

    // 記錄跳出循環(huán)前最后的一個(gè) Message 對(duì)象
    Message prev;

    // 不斷循環(huán),根據(jù)執(zhí)行時(shí)間進(jìn)行對(duì)鏈表進(jìn)行排序
    for (;;) {

        // 你沒有看錯(cuò)晒屎,這個(gè)對(duì)象就只是記錄而已喘蟆,循環(huán)里面沒有用到
        prev = p;

        // 獲取鏈表的下一個(gè)
        p = p.next;
        // 如果這個(gè)是鏈表的最后一個(gè),如果這個(gè)消息執(zhí)行時(shí)間要比鏈表的下一個(gè)要提前的話
        if (p == null || when < p.when) {
            // 跳出循環(huán)
            break;
        }
        if (needWake && p.isAsynchronous()) {
            needWake = false;
        }
    }

    // 將剛剛符合要求的對(duì)象 p 排在 msg 后面
    msg.next = p;
    // 再將 msg 排在 prev 的后面(溫馨提醒:prev 和 p 是不一樣的夷磕,p 其實(shí)等于 prev.next履肃,不信你回去看源碼)
    prev.next = msg;

    // 排序前:prev ---> p
    // 排序后:prev ---> msg ---> p
}

Message(消息) 對(duì)象已經(jīng)在 MessageQueue(消息隊(duì)列)中排序好了,那么問題來了坐桩,MessageQueue.enqueueMessage 方法壓根沒調(diào)用 Handler.handleMessage 方法尺棋?你讓我情何以堪?

糾正一個(gè)剛剛的設(shè)想

Handler.handleMessage 到底被誰調(diào)用了绵跷?請(qǐng)看下圖

handleMessage 原來是被 Handler.dispatchMessage 回調(diào)的膘螟,那么我們之前那種設(shè)想還不太對(duì)

// 剛剛的設(shè)想
msg.target.handleMessage(msg); // 錯(cuò)誤

// 現(xiàn)在的設(shè)想
msg.target.dispatchMessage(msg); // 正確

Handler 和 Looper 的關(guān)系

讓我們先來看一下 Handler 構(gòu)造函數(shù)

public class Handler {

    public Handler() {
        this(null, false);
    }

    public Handler(Callback callback) {
        this(callback, false);
    }

    public Handler(Looper looper) {
        this(looper, null, false);
    }

    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

    public Handler(boolean async) {
        this(null, async);
    }

    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 " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
}

我們先來看一下兩句重點(diǎn)代碼

mLooper = looper;
mQueue = looper.mQueue;

你會(huì)發(fā)現(xiàn),Handler 和 Looper 有很大關(guān)系碾局,就連 MessageQueue 也是 Looper 里面的對(duì)象荆残,看來還真的不簡(jiǎn)單

Looper.loop

既然如此,我上去一頓搜索净当,Looper 類中只有一個(gè)地方調(diào)用了 Handler.dispatchMessage 方法

由于這個(gè)方法太長内斯,我們把這個(gè)方法源碼單獨(dú)拎出來蕴潦,簡(jiǎn)單過一遍就好

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the loop.
 */
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();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
            SystemProperties.getInt("log.looper."
                    + Process.myUid() + "."
                    + Thread.currentThread().getName()
                    + ".slow", 0);

    boolean slowDeliveryDetected = false;

    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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        try {
            msg.target.dispatchMessage(msg);
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {
            if (slowDeliveryDetected) {
                if ((dispatchStart - msg.when) <= 10) {
                    Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                        msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {
            showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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è) Looper.loop 方法的注釋

Run the message queue in this thread. Be sure to call  {@link #quit()} to end the loop.

在這個(gè)線程中運(yùn)行消息隊(duì)列。確保調(diào)用{@link #quit()}來結(jié)束循環(huán)俘闯。

看完這個(gè)翻譯你是不是頓悟了潭苞,原來 MessageQueue 消息隊(duì)列最后是在這個(gè)方法執(zhí)行的,接下來我們分析一下里面比較重點(diǎn)的源碼

// 不斷循環(huán)
for (;;) {
    
    // 取 MessageQueue 中的 Message 對(duì)象真朗,具體方法就不帶大家看了
    Message msg = queue.next();
    if (msg == null) {
        // 直到消息隊(duì)列沒有 Message 對(duì)象了就跳出循環(huán)和退出方法
        return;
    }

    // This must be in a local variable, in case a UI event sets the logger
    final Printer logging = me.mLogging;
    if (logging != null) {
        logging.println(">>>>> Dispatching to " + msg.target + " " +
                msg.callback + ": " + msg.what);
    }

    final long traceTag = me.mTraceTag;
    long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
    long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
    if (thresholdOverride > 0) {
        slowDispatchThresholdMs = thresholdOverride;
        slowDeliveryThresholdMs = thresholdOverride;
    }
    final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
    final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

    final boolean needStartTime = logSlowDelivery || logSlowDispatch;
    final boolean needEndTime = logSlowDispatch;

    if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
        Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
    }

    final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
    final long dispatchEnd;
    try {
        // msg.target 之前說過了此疹,在 sendMessage 的時(shí)候已經(jīng)賦值自身給這個(gè)字段了
        msg.target.dispatchMessage(msg);
        dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
    } finally {
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }
}

看完源碼后總結(jié)

  • Message:消息

  • MessageQueue:消息集合

  • Looper:執(zhí)行消息

Android 技術(shù)討論 Q 群:10047167

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市遮婶,隨后出現(xiàn)的幾起案子蝗碎,更是在濱河造成了極大的恐慌,老刑警劉巖旗扑,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蹦骑,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡臀防,警方通過查閱死者的電腦和手機(jī)脊串,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來清钥,“玉大人,你說我怎么就攤上這事放闺∷钫眩” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵怖侦,是天一觀的道長篡悟。 經(jīng)常有香客問我,道長匾寝,這世上最難降的妖魔是什么搬葬? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮艳悔,結(jié)果婚禮上急凰,老公的妹妹穿的比我還像新娘。我一直安慰自己猜年,他們只是感情好抡锈,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著乔外,像睡著了一般床三。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上杨幼,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天撇簿,我揣著相機(jī)與錄音聂渊,去河邊找鬼。 笑死四瘫,一個(gè)胖子當(dāng)著我的面吹牛汉嗽,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播莲组,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诊胞,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了锹杈?” 一聲冷哼從身側(cè)響起撵孤,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎竭望,沒想到半個(gè)月后邪码,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡咬清,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年闭专,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旧烧。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡影钉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出掘剪,到底是詐尸還是另有隱情平委,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布夺谁,位于F島的核電站廉赔,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏匾鸥。R本人自食惡果不足惜蜡塌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望勿负。 院中可真熱鬧馏艾,春花似錦、人聲如沸奴愉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽躁劣。三九已至迫吐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間账忘,已是汗流浹背志膀。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來泰國打工熙宇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人溉浙。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓烫止,卻偏偏與公主長得像,于是被迫代替她去往敵國和親戳稽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子馆蠕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

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