10.2 Android消息機制分析

10.2.1 ThreadLocal的工作原理

ThreadLocal是一個線程內部的數據存儲類,通過它可以在指定的線程中存儲數據缺谴,數據存儲以后,只有在指定線程中可以獲取到存儲的數據耳鸯,對于其他線程來說則無法獲取到數據湿蛔。
源碼分析

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

    protected T initialValue() {
        return null;
    }

set(value)方法會給當前的Thread創(chuàng)建一個ThreadLocalMap,讓后以thread為key县爬,將key-value存入該map中阳啥。
get()方法會從當前Thread中獲取ThreadLocalMap,然后以Thread為key從map中取value财喳。

10.2.2 消息隊列的工作原理

MessageQueue持有Message對象察迟,Message是一個單向鏈表。
messageQueue有2個核心方法:enqueueMessage()next()
next()方法是一個無限循環(huán)方法耳高,如果沒有消息next就被阻塞扎瓶,如果有新消息,next方法會返回這條消息并將其從單鏈表中移除泌枪。

10.2.3 Looper的工作原理

Looper會不停的從messageQueue中查看是否有新消息概荷,如果有新消息就會立刻處理,否則一直就阻塞在哪里碌燕。
構造方法
構建方法創(chuàng)造了一個MessageQueue

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

創(chuàng)建Looper
prepare()方法為當前線程創(chuàng)建一個Looper

    public static void prepare() {
        prepare(true);
    }

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

開啟循環(huán) loop()方法開啟消息循環(huá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();

        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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

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

loop()解析
loop是一個死循環(huán)误证,唯一得跳出條件時MessageQueue.next()返回null。
當Looper的quite或quitSafely被調用的時候修壕,MessageQueue的quit被調用愈捅,之后消息隊列被標記位退出裝填,next會返回空慈鸠。

    // Looper 的quit方法
    public void quit() {
        mQueue.quit(false);
    }

    public void quitSafely() {
        mQueue.quit(true);
    }

拿到message后蓝谨,會執(zhí)行
msg.target.dispatchMessage(msg),這里的msg.targe是發(fā)送這條消息的Handler對象青团。
終止循環(huán)
Looper提供了quit和quitSafely兩個方法退出一個Looper像棘。
quit直接退出,quitSafely只做標記位壶冒,消息隊列中的消息處理完畢后才會安全的退出缕题。

10.2.4Handler的工作原理

無Looper構造方法
不傳入Looper的構造方法,handler中的Looper默認是當前線程的Looper胖腾,如果當前線程沒有Looper會拋出異常烟零。

    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }

    /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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;
    }

關鍵代碼mLooper = Looper.myLooper();
再來看看Looper
Looper有個ThreadLocal<Looper>的靜態(tài)成員變量sThreadLocal瘪松,在調用prepare()時會 new 一個Looper對象出來,并將它置入sThreadLocal中锨阿。
Looper的構造方法新建了一個MessageQueue宵睦,將currentThread賦值到成員變量之中。

    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

     /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
        prepare(true);
    }

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

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

有Looper構造方法
有Looper的構造方法相對簡單墅诡,直接將方法入參的Looper傳入Handler之中壳嚎。

    /**
     * Use the provided {@link Looper} instead of the default one.
     *
     * @param looper The looper, must not be null.
     */
    public Handler(Looper looper) {
        this(looper, null, false);
    }

    /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     */
    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

    /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.  Also set whether the handler
     * should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

發(fā)送消息
無論是post(Runnable)還是sendMessage(Message)最終都是將數據轉化為Message,存入MessageQueue之中末早。

Handler.png

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末烟馅,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子然磷,更是在濱河造成了極大的恐慌郑趁,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件姿搜,死亡現(xiàn)場離奇詭異寡润,居然都是意外死亡,警方通過查閱死者的電腦和手機舅柜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進店門梭纹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人致份,你說我怎么就攤上這事变抽。” “怎么了知举?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵且轨,是天一觀的道長题翻。 經常有香客問我唯绍,道長黎做,這世上最難降的妖魔是什么害捕? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任茶凳,我火速辦了婚禮匿辩,結果婚禮上阳准,老公的妹妹穿的比我還像新娘芳悲。我一直安慰自己立肘,他們只是感情好,可當我...
    茶點故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布名扛。 她就那樣靜靜地躺著谅年,像睡著了一般。 火紅的嫁衣襯著肌膚如雪肮韧。 梳的紋絲不亂的頭發(fā)上融蹂,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天旺订,我揣著相機與錄音,去河邊找鬼超燃。 笑死区拳,一個胖子當著我的面吹牛,可吹牛的內容都是我干的意乓。 我是一名探鬼主播樱调,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼届良!你這毒婦竟也來了笆凌?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤伙窃,失蹤者是張志新(化名)和其女友劉穎菩颖,沒想到半個月后,有當地人在樹林里發(fā)現(xiàn)了一具尸體为障,經...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡晦闰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了鳍怨。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片呻右。...
    茶點故事閱讀 38,622評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖鞋喇,靈堂內的尸體忽然破棺而出声滥,到底是詐尸還是另有隱情,我是刑警寧澤侦香,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布落塑,位于F島的核電站,受9級特大地震影響罐韩,放射性物質發(fā)生泄漏憾赁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一散吵、第九天 我趴在偏房一處隱蔽的房頂上張望龙考。 院中可真熱鬧,春花似錦矾睦、人聲如沸晦款。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽缓溅。三九已至,卻和暖如春赁温,著一層夾襖步出監(jiān)牢的瞬間坛怪,已是汗流浹背州藕。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留酝陈,地道東北人床玻。 一個月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像沉帮,于是被迫代替她去往敵國和親锈死。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內容