Handler源碼分析筆記

Handler

我們都知道Handler由Message善玫、MessageQueue禁悠、HandlerLooper組成粉私,接下來我們帶著問題绷旗,從源碼中尋找 Handler 的具體流程與實現(xiàn)。

問題

  • 消息是如何發(fā)送出去的际乘?
  • 消息時如何被得到的坡倔?
  • 輪詢器的啟動在什么時候?
  • 輪詢器與消息隊列的綁定是如何建立的脖含?
  • 如何確弊锼總是能夠在對應的線程中獲取到正確的輪詢器實例?
  • 對消息隊列的操作养葵,消費者和生產(chǎn)者征堪,主線程與子線程如何進行通信?
  • Handler只能用于主線程UI更新关拒?

解析

首先從輪詢器的啟動開始佃蚜,所有的java程序都有一個main方法作為程序的入口庸娱,而Android中這個main方法在ActivityThread中

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

        Looper.prepareMainLooper();

        ...
            
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

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

在代碼中我們可以看到 Looper.prepareMainLooper()和Looper.loop() 兩個方法

先從Looper.prepareMainLooper()進行分析

    private static Looper sMainLooper;  // guarded by Looper.class 保存Looper類
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

在其中prepareMainLooper,Looper將全局靜態(tài)變量 sMainLooper 賦值和調(diào)用了 prepare() 方法

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    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));
    }
    //myLooper就是調(diào)用了sThreadLocal的get方法
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

在 prepare 中調(diào)用了全局靜態(tài)變量 sThreadLocal 的 set 方法

那么ThreadLocal是什么呢谐算?

ThreadLocal本質(zhì)是一個Map熟尉,不過其中的 key 值是線程 Thread ,它通過線程來存儲和讀取數(shù)據(jù)洲脂。正如其名斤儿,用來存儲線程本地數(shù)據(jù)【避免其他線程讀取或修改】。

可就是說在此處恐锦,sThreadLocal 中存儲了與主線程對應的 Looper 實例往果,只要是主線程中調(diào)用sThreadLocal 的get方法就能獲取這個輪詢器,若是其他子線程就獲取不到這個輪詢器

然后就到了講解 Looper.loop() 一铅,也就是在這里開始死循環(huá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;
    
        ...
            
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ...

            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);
                }
            }
            ...
            /*
            * 經(jīng)過上述步驟消息都未被處理,于是將其回收
            */
            msg.recycleUnchecked();
        }
    }

在 loop 中我們主要看到 MessageQueue 潘飘、 msg.target.dispatchMessage(msg) 這三處地方

我們先看 msg.target.dispatchMessage(msg) 之后飘蚯,回來了解 MessageQueue

public final class Message implements Parcelable {
    ...
    Handler target;
    Runnable callback;
    ...
}

從 Message 中了解 target 就是 Handler,而 callback 是用戶設置的回調(diào)任務福也,只要不設置這個 callback 就會進入 handleMessage

public class Handler {
    ...
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //這里調(diào)用了用戶自定義的handleMessage去處理業(yè)務邏輯
            handleMessage(msg);
        }
    }
    ...
}

這里我們看到了消息時如何被得回應的,那么我們只需要知道 Message 是怎么發(fā)送的和在什么時候給 target 賦值確保Handler對象不出錯攀圈。

Message 是如何發(fā)送的暴凑?這個問題想必都知道答案

public class Handler {
    final Looper mLooper;
    final MessageQueue mQueue;
    ...
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    //最終進入該方法,此處就出現(xiàn)了 MessageQueue
    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);
    }
    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;//在此處Handler給Message的target賦值
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    ...
}

經(jīng)過一層一層的調(diào)用,最終Handler調(diào)用了 enqueueMessage 方法赘来,將 Message 放入它的全局變量MessageQueue中现喳,且將Message的target賦值為this【發(fā)送消息的Handler本身】

那么我們知道了發(fā)送的消息最終去向【MessageQueue】,那么Handler中的MessageQueue又是什么時候初始化的犬辰?

    //我們平常使用的Handler無參構(gòu)造函數(shù)最終都會到這里
    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());
            }
        }
        //此處就是為什么子線程不能創(chuàng)建Handler的原因
        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;
    }

mLooper = Looper.myLooper() 之前我們分析過 myLooper 就是調(diào)用了sThreadLocal的get方法嗦篱,此處只有主線程才有對應的 Looper 實例存在,這也就是為什么子線程中不能用無參構(gòu)造方法實例化Handler幌缝,如果創(chuàng)建會報下列錯誤提示

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

當然也不是沒有解決方案灸促,不是沒有 Looper 報錯嗎,那就給唄:选T≡浴!解決方案

繼續(xù)向下轿偎,我們看到 mQueue = mLooper.mQueue 典鸡,也就是說 MessageQueue 是從Looper中獲取的

public final class Looper {
    private static Looper sMainLooper;  // guarded by Looper.class
    final MessageQueue mQueue;
    final Thread mThread;
    ...
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
    ...
}

嗯,MessageQueue 對象在私有構(gòu)造函數(shù)中就已經(jīng)實例化了坏晦,那么還記得什么時候調(diào)用了Looper的構(gòu)造函數(shù)嗎萝玷?

繞了一圈終于到了講解 MessageQueue 了

public final class MessageQueue {
    Message mMessages;//
    ...
    boolean enqueueMessage(Message msg, long when) {
        ...
        synchronized (this) {
            if (mQuitting) {//是否退出嫁乘,只有調(diào)用了quit方法后是true
                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();
            //SystemClock.uptimeMillis() + delayMillis
            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;
    }
}

此時你可能有些疑惑,不是隊列嗎球碉,那么為什么沒有數(shù)組或者List呢蜓斧?因為 MessageQueue 采用鏈表的方式實現(xiàn)隊列。

public final class Message implements Parcelable {
    ...
    // sometimes we store linked lists of these things
    /*package*/ Message next;
    //最大Message池為50個
    private static final int MAX_POOL_SIZE = 50;
    ...
}

我們將 if 語句分開看

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

首先Message p被賦值為全局變量 mMessages【我稱其為“即將發(fā)送Message”】如果

  • “即將發(fā)送Message”是null
  • msg 的 when 是0 【when = SystemClock.uptimeMillis() + delayMillis】
  • msg 的 when 小于“即將發(fā)送Message”的 when 【 msg 發(fā)送事件的等待時間 小于 mMessages】

其中一個成立汁尺,將 msg 的 next 指向 p 法精,在將 mMessages 賦值為 msg【實際上就是將msg放在隊列最前面】

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

到else,基本就是 mMessages有值且 msg 發(fā)送事件的等待時間 大于 mMessages痴突,于是就把 msg 放入鏈表中搂蜓,通過循環(huán)將 msg 放入鏈表的合適位置,確保隊列中的元素等待時間是遞增的

既然已經(jīng)講了存放辽装,那么就該到讀取了

    Message next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

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

                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    //基本不會進入這個if
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

此處我們看到了MessageQueue調(diào)用了 native 方法【就是java調(diào)用了c方法】帮碰,其具體的實現(xiàn)在 /frameworks/base/core/jni/android_os_MessageQueue.cpp 點擊此處查看

//可以理解為阻塞,ptr相當于Message指針拾积,timeoutMillis阻塞時間
private native void nativePollOnce(long ptr, int timeoutMillis); 
//喚醒殉挽,之前在enqueueMessage中有調(diào)用該方法喚醒
private native static void nativeWake(long ptr);

之后我們主要看 next 對 return 有關的部分

final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//msg 對應的 Handler 被銷毀,于是取出隊列中的下一個 Message
if (msg != null && msg.target == null) {
    do {
        prevMsg = msg;
        msg = msg.next;
    } while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
    //還沒有到 msg 的發(fā)送時間拓巧,需要阻塞等待
    if (now < msg.when) {
        // 下一條消息未準備好斯碌。設置一個超時時間,當它準備好時喚醒肛度。
        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
    } else {
        // 到 msg 的發(fā)送時間
        mBlocked = false;
        //將 mMessages 變?yōu)?msg 的 next
        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 {
    // nextPollTimeoutMillis = -1 代表nativePollOnce將一直阻塞直到被喚醒
    nextPollTimeoutMillis = -1;
}

到了這里Handler的源碼分析就結(jié)束了傻唾,可以再回去看看Handler的流程圖是不是會有新的感悟

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市承耿,隨后出現(xiàn)的幾起案子冠骄,更是在濱河造成了極大的恐慌,老刑警劉巖加袋,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件凛辣,死亡現(xiàn)場離奇詭異,居然都是意外死亡职烧,警方通過查閱死者的電腦和手機扁誓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蚀之,“玉大人跋理,你說我怎么就攤上這事√褡埽” “怎么了前普?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長壹堰。 經(jīng)常有香客問我拭卿,道長骡湖,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任峻厚,我火速辦了婚禮响蕴,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘惠桃。我一直安慰自己浦夷,他們只是感情好,可當我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布辜王。 她就那樣靜靜地躺著劈狐,像睡著了一般。 火紅的嫁衣襯著肌膚如雪呐馆。 梳的紋絲不亂的頭發(fā)上肥缔,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天,我揣著相機與錄音汹来,去河邊找鬼续膳。 笑死,一個胖子當著我的面吹牛收班,可吹牛的內(nèi)容都是我干的坟岔。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼摔桦,長吁一口氣:“原來是場噩夢啊……” “哼社付!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起酣溃,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎纪隙,沒想到半個月后赊豌,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡绵咱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年碘饼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片悲伶。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡艾恼,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出麸锉,到底是詐尸還是另有隱情钠绍,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布花沉,位于F島的核電站柳爽,受9級特大地震影響媳握,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜磷脯,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一蛾找、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧赵誓,春花似錦打毛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至绑雄,卻和暖如春展辞,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背万牺。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工罗珍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人脚粟。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓覆旱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親核无。 傳聞我的和親對象是個殘疾皇子扣唱,可洞房花燭夜當晚...
    茶點故事閱讀 45,876評論 2 361

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