本篇文章已授權(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í)行消息