Handler 原理:
首先sendMessage()以及 sendMessageDelayed()最后調(diào)用的都是 sendMessageDelayed(),接著開始總體流程
遍歷鏈表: 首先判斷鏈表里有沒有message,如果里面是空的或者傳入的msg執(zhí)行的時間比頭message要早,則把msg放到鏈表的頭部,( 比如send兩次message,先執(zhí)行的有延時,后執(zhí)行的沒延時,這個時候就要把后執(zhí)行的message放到最前面) 接著遍歷鏈表,根據(jù)執(zhí)行的事件去調(diào)整message的位置:
第一次添加數(shù)據(jù)到隊列中,或者當(dāng)前 msg 的時間小于 mMessages 的時間
// p為隊列中頭部msg
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
// 把當(dāng)前 msg 添加到鏈表的第一個
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// 不是第一次添加數(shù)據(jù),并且 msg 的時間 大于 mMessages(頭指針) 的時間
// 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) { // 根據(jù)執(zhí)行時間判斷應(yīng)該插到哪個位置
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
// 把當(dāng)前 msg 插入到列表中
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
Looper
Looper是通過不斷循環(huán)去獲取message的,要使用handler,子線程中必須調(diào)用looper.prepare()以及 looper.loop()。主線程中默認(rèn)有一個looper,ActivityThread中系統(tǒng)已經(jīng)初始化了一個looper,下面是具體邏輯代碼
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
// 一個死循環(huán)
for (;;) {
// 不斷的從消息隊列里面取消息
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
// 通過 target 去 dispatchMessage 而 target 就是綁定的 Handler
// 到這里也就完成了消息的傳遞流程
msg.target.dispatchMessage(msg);
} finally {
// 消息回收循環(huán)利用
msg.recycleUnchecked();
}
}
}
在這里loop的死循環(huán)涉及到pipe知識就不深入探討,如下圖

image.gif

image.png