Android源碼分析之Handler

Handler在Android開發(fā)中無處不在隶校,它的使用方式想必大家都已經(jīng)很熟練了漏益,這里主要是分析它的原理。

我們從ActivityThread#main方法開始深胳,一步步理解Handler的機制绰疤。相關(guān)代碼如下:

/frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
    ...

    Looper.prepareMainLooper();

    ...
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

ActivityThread初始化時就通過Looper建立了消息循環(huán)機制,先看下初始化部分舞终,相關(guān)代碼如下:

/frameworks/base/core/java/android/os/Looper.java

public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        // 確保主線程僅有一個Looper實例
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();
    }
}

private static void prepare(boolean quitAllowed) {
    // 確保線程僅對應一個Looper
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

這里通過ThreadLocal確保線程安全轻庆,且保證任何線程只能對應一個Looper實例。Looper實例化時敛劝,就確定了它所在的線程余爆,同時創(chuàng)建了一個MessageQueue,代碼如下:

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

MessageQueue稍后再研究夸盟,先看下Looper#loop的實現(xiàn)蛾方,代碼如下:

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

            ...
            try {
                // 分發(fā)消息
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            ...
            msg.recycleUnchecked();
        }
    }

這里建立了一個無限循環(huán)桩砰,不斷地從MessageQueue中獲取消息,然后進行分發(fā)释簿,而我們使用的Handler并沒有直接綁定在Looper中亚隅,而是綁定在msg.target變量里,這樣做的好處是可以創(chuàng)建多個Handler庶溶。下面我們轉(zhuǎn)到MessageQueue中煮纵,了解下MessageQueue#next方法沉删,代碼如下:

/frameworks/base/core/java/android/os/MessageQueue.java

Message next() {
    ...

    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }

        nativePollOnce(ptr, nextPollTimeoutMillis);

        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages; // 當前消息
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                // 找到下一個異步消息,忽略同步消息
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    // 沒到msg分發(fā)時間
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }

            ...
        }

        ...
    }
}

這里通過for循環(huán)不斷的獲取消息醉途,然后等待消息分發(fā)時間到之后將消息分發(fā)出去矾瑰,這樣消息循環(huán)就建立好了。不過這里我們看到一段對異步消息的處理隘擎,為了更好的理解這段的作用殴穴,我們在文末再分析。接下來就應該通過Handler來發(fā)送消息和處理消息货葬,Handler發(fā)送消息的方法有很多種采幌,我們主要使用的有以下幾種:

  • handler.sendMessage(msg)
  • handler.sendMessageDelayed(msg, delay)
  • handler.post(runnable)
  • handler.postDelayed(runnable, delay)

除了以上幾個,還有幾個類似的方法震桶,甚至還有一個Handler#sendMessageAtFrontOfQueue方法休傍,可以在消息隊列的最前面插入消息,不過這些方法的原理都是一致的蹲姐,我們著重分析Handler#sendMessageHandler#post這兩個方法磨取。代碼如下:

/frameworks/base/core/java/android/os/Handler.java

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

public final boolean post(Runnable r)
{
    return  sendMessageDelayed(getPostMessage(r), 0);
}

可以看到,它們最終都是調(diào)用了Handler#sendMessageDelayed方法柴墩,只是通過post方式最終將Runnable轉(zhuǎn)成了Message對象忙厌,具體的做法如下:

private static Message getPostMessage(Runnable r) {
    // 從一個全局的對象池里獲取Message對象,可以重復使用江咳,這樣就節(jié)省了new對象的開支
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

也就是說這個Runnable實例就是作為Messagecallback的逢净。繼續(xù)看Handler#sendMessageDelayed方法,代碼如下:

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;
    ...
    return enqueueMessage(queue, msg, uptimeMillis);
}

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

最終歼指,所有的方法都會調(diào)用到這個Handler#enqueueMessage方法爹土,將Handler本身作為Messagetarget參數(shù),然后將消息入隊踩身,最后在Looper中分發(fā)胀茵。接下來看下入隊的操作,代碼如下:

/frameworks/base/core/java/android/os/MessageQueue.java

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) {
            // 新消息需要更早分發(fā)
            // 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();
            // 根據(jù)時間順序惰赋,將消息插入到合適的位置
            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;
}

通過以上代碼我們發(fā)現(xiàn)宰掉,消息在入隊時,就已經(jīng)按照時間順序排列好了赁濒,最后到了分發(fā)階段,分發(fā)是通過Handler#dispatchMessage完成的孟害,代碼如下:

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

private static void handleCallback(Message message) {
    message.callback.run();
}

原來拒炎,如果在發(fā)送Message時設(shè)置了callback,就會由我們設(shè)置的Runnable來處理挨务,否則击你,就通過Handler初始化時指定的Callback處理玉组,如果都沒有設(shè)置,就通過Handler#handleMessage方法來處理丁侄。這個mCallback是在構(gòu)造函數(shù)中實例化的惯雳,我們看幾個構(gòu)造方法就明白了:

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(Looper looper, Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

現(xiàn)在我們來解釋下前面提到的異步消息。通過向MessageQueue中發(fā)送消息就可以讓事件按照指定的時間和順序來執(zhí)行鸿摇,但如果想要讓消息有優(yōu)先級區(qū)別呢石景?可以使用MessageQueue#postSyncBarrier方法,代碼如下:

public int postSyncBarrier() {
    return postSyncBarrier(SystemClock.uptimeMillis());
}

private int postSyncBarrier(long when) {
    // Enqueue a new sync barrier token.
    // We don't need to wake the queue because the purpose of a barrier is to stall it.
    synchronized (this) {
        final int token = mNextBarrierToken++;
        final Message msg = Message.obtain();
        msg.markInUse();
        msg.when = when;
        msg.arg1 = token;

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

看起來這個方法也沒有什么特別的地方拙吉,唯一的區(qū)別就是消息沒有target潮孽,也就是沒有Handler對象,MessageQueue在執(zhí)行next方法時就會走到if (msg != null && msg.target == null)中筷黔,此時它會忽略其間所有的同步消息往史,直到找到一個異步消息并開始執(zhí)行,這個做法稱之為同步屏障佛舱。調(diào)用此方法后可以得到一個token值椎例,可以通過這個值取消屏障。然后我們就可以向MessageQueue發(fā)送一個異步消息请祖,優(yōu)先執(zhí)行此事件了粟矿。MessageQueue#postSyncBarrier通常需要與MessageQueue#removeSyncBarrier成對使用,否則就再也接收不到同步消息了损拢。目前陌粹,這個方法被標記為HIDE,在API層面無法調(diào)用福压。

RootViewImpl#scheduleTraversals方法中掏秩,為了讓Android系統(tǒng)能夠更快的響應UI的刷新事件,就使用了此方法荆姆,代碼如下:

void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}

具體的分析請看Android源碼分析之Activity啟動與View繪制流程(一)蒙幻。

至此,我們對Handler機制就有了清晰的認識胆筒,它并不復雜邮破,但是功能十分強大,掌握它的原理以后使用時會更加順手。

Android源碼分析之Touch事件分發(fā)機制

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市启绰,隨后出現(xiàn)的幾起案子颓芭,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡镊辕,警方通過查閱死者的電腦和手機油够,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來征懈,“玉大人石咬,你說我怎么就攤上這事÷舭ィ” “怎么了鬼悠?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長棉饶。 經(jīng)常有香客問我厦章,道長,這世上最難降的妖魔是什么照藻? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任袜啃,我火速辦了婚禮,結(jié)果婚禮上幸缕,老公的妹妹穿的比我還像新娘群发。我一直安慰自己,他們只是感情好发乔,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布熟妓。 她就那樣靜靜地躺著,像睡著了一般栏尚。 火紅的嫁衣襯著肌膚如雪起愈。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天译仗,我揣著相機與錄音抬虽,去河邊找鬼。 笑死纵菌,一個胖子當著我的面吹牛阐污,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播咱圆,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼笛辟,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了序苏?” 一聲冷哼從身側(cè)響起手幢,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎杠览,沒想到半個月后弯菊,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡踱阿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年管钳,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片软舌。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡才漆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出佛点,到底是詐尸還是另有隱情醇滥,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布超营,位于F島的核電站鸳玩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏演闭。R本人自食惡果不足惜不跟,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望米碰。 院中可真熱鬧窝革,春花似錦、人聲如沸吕座。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽吴趴。三九已至漆诽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锣枝,已是汗流浹背厢拭。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留惊橱,地道東北人蚪腐。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像税朴,于是被迫代替她去往敵國和親回季。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359

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