一、常見(jiàn)使用場(chǎng)景
消息機(jī)制中主要用于多線(xiàn)程的通訊,在 Android 開(kāi)發(fā)中最常見(jiàn)的使用場(chǎng)景是:在子線(xiàn)程做耗時(shí)操作,操作完成后需要在主線(xiàn)程更新 UI(子線(xiàn)程不能直接修改 UI)。這時(shí)就需要用到消息機(jī)制來(lái)完成子線(xiàn)程和主線(xiàn)程的通訊。
如以下代碼片段所示:
public class MainActivity extends AppCompatActivity {
private TextView tvText;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvText.setText(msg.obj.toString());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvText = (TextView) findViewById(R.id.tv_text);
new Thread() {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg = Message.obtain();
msg.obj = Thread.currentThread().getName();
mHandler.sendMessage(msg);
}
}.start();
}
}
子線(xiàn)程阻塞 10 秒后發(fā)送消息更新 TextView,TextView 顯示來(lái)源的線(xiàn)程名。
這里有兩個(gè)限制:
不能讓阻塞發(fā)生在主線(xiàn)程,否則會(huì)發(fā)生 ANR
不能在子線(xiàn)程更新 TextView。
所以只能在子線(xiàn)程阻塞 10 秒,然后通過(guò) Handler 發(fā)送消息,Handler 處理獲取到的消息并在主線(xiàn)程更新 TextView。
二、消息機(jī)制分析
1. 準(zhǔn)備階段
1.1 Handler 構(gòu)造方法
private Handler mHandler = new Handler() {
...
};
查看 Handler 的源碼:
...
public Handler() {
this(null, false);
}
...
/**
* @hide 該構(gòu)造方法是隱藏的,無(wú)法直接調(diào)用
*/
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;
}
...
Handler 的構(gòu)造方法需要傳入兩個(gè)參數(shù),第一個(gè)參數(shù)是 Handler.Callback 接口的實(shí)現(xiàn),第二個(gè)參數(shù)是標(biāo)志傳遞的 Message 是否是異步。
構(gòu)造方法內(nèi)部首先會(huì)檢查 Handler 的使用是否可能存在內(nèi)存泄漏的問(wèn)題,如果存在會(huì)發(fā)出一個(gè)警告:
所以在使用 Handler 的時(shí)候一般聲明為靜態(tài)內(nèi)部類(lèi)或使用弱引用的方式。
接著會(huì)調(diào)用 Looper.myLooper() 獲取到 Looper 對(duì)象,并判斷該 Looper 對(duì)象是否為 null,如果為 null 則拋出異常;如果不為 null 則進(jìn)行相應(yīng)的賦值操作。由此可知 Looper.myLooper() 方法并不會(huì)構(gòu)造一個(gè) Looper 對(duì)象,而是從某個(gè)地方獲取到一個(gè) Looper 對(duì)象。
所以,在創(chuàng)建 Handler 對(duì)象時(shí)必須先創(chuàng)建 Looper 對(duì)象。
1.2 Looper 對(duì)象的創(chuàng)建
下面查看 Looper 源碼:
...
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));
}
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
...
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
...
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
...
從 Looper 的源碼可知,Looper 類(lèi)中對(duì)外部提供兩個(gè)方法用于創(chuàng)建 Looper 對(duì)象:prepare() 和 prepareMainLooper(),并將創(chuàng)建的 Looper 對(duì)象保存到 sThreadLocal 中。myLooper() 方法獲取 Looper 對(duì)象也是從 sThreadLocal 中獲取。
sThreadLocal 是一個(gè)ThreadLocal 對(duì)象,ThreadLocal 用于提供線(xiàn)程局部變量,在多線(xiàn)程環(huán)境可以保證各個(gè)線(xiàn)程里的變量獨(dú)立于其它線(xiàn)程里的變量。也就是說(shuō) ThreadLocal 可以為每個(gè)線(xiàn)程創(chuàng)建一個(gè)【單獨(dú)的變量副本】,相當(dāng)于一個(gè)線(xiàn)程的 private static 類(lèi)型變量。
在 Looper 的真正創(chuàng)建對(duì)象方法 prepare(boolean quitAllowed) 中,會(huì)先判斷當(dāng)前線(xiàn)程是否已經(jīng)有 Looper 對(duì)象,沒(méi)有時(shí)才可以創(chuàng)建并保存到當(dāng)前線(xiàn)程中,每個(gè)線(xiàn)程只允許有一個(gè) Looper。
上面的示例代碼中是在主線(xiàn)程中實(shí)例化 Handler 的,但是并沒(méi)有調(diào)用 Looper 的創(chuàng)建方法,而且也沒(méi)有拋出異常,說(shuō)明主線(xiàn)程中是有 Looper 對(duì)象的。
那么主線(xiàn)程中的 Lopper 對(duì)象是從哪里來(lái)的呢?
在 Looper 的 prepareMainLooper() 方法注釋中可以看到這樣一句話(huà):
The main looper for your application is created by the Android environment, so you should never need to call this function yourself.
意思是:應(yīng)用程序的主 Looper 由 Android 環(huán)境創(chuàng)建,不應(yīng)該自己調(diào)用該方法。
由此可知,在 Android 系統(tǒng)源碼中應(yīng)該會(huì)調(diào)用該方法,通過(guò)查找該方法的使用發(fā)現(xiàn),在 ActivityThread 類(lèi)的 main 方法中調(diào)用了 Looper.prepareMainLooper():
public static void main(String[] args) {
...
Looper.prepareMainLooper();
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
所以在應(yīng)用程序啟動(dòng)時(shí)就已經(jīng)為主線(xiàn)程創(chuàng)建了一個(gè) Looper 對(duì)象。
2. 發(fā)送消息
繼續(xù)分析示例代碼,在子線(xiàn)程阻塞結(jié)束后會(huì)創(chuàng)建一個(gè) Message 對(duì)象,然后使用 Handler 發(fā)送該 Message 對(duì)象。
...
Message msg = Message.obtain();
msg.obj = Thread.currentThread().getName();
mHandler.sendMessage(msg);
...
2.1 創(chuàng)建 Message 對(duì)象
調(diào)用 Message 的 obtain() 方法創(chuàng)建 Message 對(duì)象。
查看 Message 的源碼:
...
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
...
public Message() {
}
...
Message 是消息機(jī)制中消息的載體,為了優(yōu)化性能,避免重復(fù) Message 的創(chuàng)建,Message 使用了消息池機(jī)制,當(dāng)調(diào)用 obtain() 方法時(shí),會(huì)先嘗試從消息池中獲取一個(gè) Message 對(duì)象,消息池中沒(méi)有時(shí)才創(chuàng)建新的對(duì)象;Message 對(duì)象使用完后會(huì)重新回收到消息池中。Message 的消息池使用了鏈表的數(shù)據(jù)結(jié)構(gòu),Message 類(lèi)本身時(shí)支持鏈表結(jié)構(gòu)的。
所以在創(chuàng)建 Message 對(duì)象時(shí)不要直接使用構(gòu)造方法。
創(chuàng)建好 Message 對(duì)象后,可以給 Message 的一些屬性賦值,用于描述該消息或攜帶數(shù)據(jù)。
2.2 Handler 發(fā)送消息
調(diào)用 Handler 的 sendMessage(Message msg) 方法發(fā)送消息。
通過(guò)查看 Handler 的源碼可知,在 Handler 中有許多發(fā)送消息的方法,所有的發(fā)送消息方法最終都會(huì)調(diào)用 enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) 方法。
...
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);
}
...
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;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
首先給 Message 的 target 屬性賦值,即當(dāng)前的 Handler;然后根據(jù) Handler 的 mAsynchronous 值設(shè)置該 Message 是否是異步的,mAsynchronous 的值在 Handler 實(shí)例化時(shí)被賦值;最后調(diào)用 MessageQueue 的 enqueueMessage(Message msg, long when) 方法。
可以看出在 Handler 中也只是對(duì) Message 對(duì)象的屬性進(jìn)行了相關(guān)賦值操作,最終是調(diào)用了 MessageQueue 的 enqueueMessage(Message msg, long when) 方法。
2.3 MessageQueue
enqueueMessage() 方法中的 MessageQueue 對(duì)象來(lái)自于 Handler 的 mQueue 屬性:
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);
}
而 mQueue 屬性在 Handler 實(shí)例化時(shí)賦值的:
public Handler(Callback callback, boolean async) {
...
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;
}
mQueue 是 Looper 中的 MessageQueue 對(duì)象,在 Looper 創(chuàng)建時(shí)被實(shí)例化:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
查看 MessageQueue 的構(gòu)造方法:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
MessageQueue 是消息隊(duì)列,Handler 發(fā)送消息其實(shí)就是將 Message 對(duì)象插入到消息隊(duì)列中,該消息隊(duì)列也是使用了鏈表的數(shù)據(jù)結(jié)構(gòu)。同時(shí) Message 也是消息機(jī)制中 Java 層和 native 層的紐帶,這里暫且不關(guān)心 native 層相關(guān)實(shí)現(xiàn)。
MessageQueue 在實(shí)例化時(shí)會(huì)傳入 quitAllowed 參數(shù),用于標(biāo)識(shí)消息隊(duì)列是否可以退出,由 ActivityThread 中 Looper 的創(chuàng)建可知,主線(xiàn)程的消息隊(duì)列不可以退出。
MessageQueue 插入消息:
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) { // target 即 Handler 不允許為 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) { // 是否正在退出消息隊(duì)列
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle(); // 回收 Message,回收到消息池
return false;
}
msg.markInUse(); // 標(biāo)記為正在使用
msg.when = when;
Message p = mMessages; // 獲取當(dāng)前消息隊(duì)列中的第一條消息
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// 消息隊(duì)列為空 或 新消息的觸發(fā)時(shí)間為 0 或 新消息的觸發(fā)時(shí)間比消息隊(duì)列的第一條消息的觸發(fā)時(shí)間早
// 將新消息插入到隊(duì)列的頭,作為消息隊(duì)列的第一條消息。
msg.next = p;
mMessages = msg;
needWake = mBlocked; // 當(dāng)阻塞時(shí)需要喚醒
} else {
// 將新消息插入到消息隊(duì)列中(非隊(duì)列頭)
// 當(dāng)阻塞 且 消息隊(duì)列頭是 Barrier 類(lèi)型的消息(消息隊(duì)列中一種特殊的消息,可以看作消息屏障,用于攔截同步消息,放行異步消息) 且 當(dāng)前消息是異步的 時(shí)需要喚醒
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
// 循環(huán)消息隊(duì)列,比較新消息的觸發(fā)時(shí)間和隊(duì)列中消息的觸發(fā)時(shí)間,將新消息插入到合適的位置
for (;;) {
prev = p; // 將前一條消息賦值給 prev
p = p.next; // 將下一條消息賦值給 p
if (p == null || when < p.when) {
// 如果已經(jīng)是消息隊(duì)列中的最后一條消息 或 新消息的觸發(fā)時(shí)間比較早 則退出循環(huán)
break;
}
if (needWake && p.isAsynchronous()) {
// 需要喚醒 且 下一條消息是異步的 則不需要喚醒
needWake = false;
}
}
// 將新消息插入隊(duì)列
msg.next = p;
prev.next = msg;
}
if (needWake) {
// 如果需要喚醒調(diào)用 native 方法喚醒
nativeWake(mPtr);
}
}
return true;
}
MessageQueue 根據(jù)消息的觸發(fā)時(shí)間,將新消息插入到合適的位置,保證所有的消息的時(shí)間順序。
3. 處理消息
消息的發(fā)送已經(jīng)分析過(guò)了,下面需要分析的是如何獲取消息并處理消息,繼續(xù)分析實(shí)例代碼:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvText.setText(msg.obj.toString());
}
};
從示例代碼中可以看到 Handler 的 handleMessage(Message msg) 負(fù)責(zé)處理消息,但是并沒(méi)有看到是如何獲取到消息的。需要在 Handler 的源碼中查找是在哪里調(diào)用 handleMessage(Message msg) 方法的。
通過(guò)在 Handler 的源碼中查找,發(fā)現(xiàn)是在 dispatchMessage(Message msg) 方法中調(diào)用 handleMessage(Message msg) 的。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
3.1 Looper 循環(huán)從消息隊(duì)列中取消息
dispatchMessage(Message msg) 方法中,根據(jù)不同的情況調(diào)用不同的消息處理方法。繼續(xù)向上查找 dispatchMessage(Message msg) 的引用,發(fā)現(xiàn)是在 Looper 的 loop() 方法中調(diào)用的,而在之前分析 Looper 的創(chuàng)建時(shí),可以知道在 ActivityThread 的 main 方法中有調(diào)用 loop() 方法。
public static void main(String[] args) {
...
Looper.prepareMainLooper();
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
下面分析 loop() 方法:
public static void loop() {
final Looper me = myLooper(); // 獲取當(dāng)前線(xiàn)程的 Looper 對(duì)象
if (me == null) { // 當(dāng)前線(xiàn)程沒(méi)有 Looper 對(duì)象則拋出異常
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue; // 獲取到當(dāng)前線(xiàn)程的消息隊(duì)列
// 清空遠(yuǎn)程調(diào)用端進(jìn)程的身份,用本地進(jìn)程的身份代替,確保此線(xiàn)程的身份是本地進(jìn)程的身份,并跟蹤該身份令牌
// 這里主要用于保證消息處理是發(fā)生在當(dāng)前 Looper 所在的線(xiàn)程
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// 無(wú)限循環(huán)
for (;;) {
Message msg = queue.next(); // 從消息隊(duì)列中獲取消息,可能會(huì)阻塞
if (msg == null) {
// 沒(méi)有消息則退出循環(huán),正常情況下不會(huì)退出的,只會(huì)阻塞在上一步,直到有消息插入并喚醒返回消息
return;
}
// 默認(rèn)為 null,可通過(guò) setMessageLogging() 方法來(lái)指定輸出,用于 debug 功能
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// 開(kāi)始跟蹤,并寫(xiě)入跟蹤消息,用于 debug 功能
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
// 通過(guò) Handler 分發(fā)消息
msg.target.dispatchMessage(msg);
} finally {
// 停止跟蹤
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// 確保在分發(fā)消息的過(guò)程中線(xiàn)程的身份沒(méi)有改變,如果改變則發(fā)出警告
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(); // 回收消息,將 Message 放入消息池
}
}
在 loop() 方法中,會(huì)不停的循環(huán)以下操作:
調(diào)用當(dāng)前線(xiàn)程的 MessageQueue 對(duì)象的 next() 方法獲取消息
通過(guò)消息的target,即 Handler 分發(fā)消息
回收消息,將分發(fā)后的消息放入消息池
3.1 從消息隊(duì)列中獲取消息
在 loop() 方法中獲取消息時(shí)有可能會(huì)阻塞,來(lái)看下 MessageQueue 的 next() 方法的實(shí)現(xiàn):
Message next() {
// 如果消息隊(duì)列退出,則直接返回
// 正常運(yùn)行的應(yīng)用程序主線(xiàn)程的消息隊(duì)列是不會(huì)退出的,一旦退出則應(yīng)用程序就會(huì)崩潰
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // 記錄空閑時(shí)處理的 IdlerHandler 數(shù)量,可先忽略
int nextPollTimeoutMillis = 0; // native 層使用的變量,設(shè)置的阻塞超時(shí)時(shí)長(zhǎng)
// 開(kāi)始循環(huán)獲取消息
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// 調(diào)用 native 方法阻塞,當(dāng)?shù)却齨extPollTimeoutMillis時(shí)長(zhǎng),或者消息隊(duì)列被喚醒,都會(huì)停止阻塞
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// 嘗試獲取下一條消息,獲取到則返回該消息
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages; // 獲取消息隊(duì)列中的第一條消息
if (msg != null && msg.target == null) {
// 如果 msg 為 Barrier 類(lèi)型的消息,則攔截所有同步消息,獲取第一個(gè)異步消息
// 循環(huán)獲取第一個(gè)異步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// 如果 msg 的觸發(fā)時(shí)間還沒(méi)有到,設(shè)置阻塞超時(shí)時(shí)長(zhǎng)
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 獲取消息并返回
mBlocked = false;
if (prevMsg != null) {
// 如果 msg 不是消息隊(duì)列的第一條消息,上一條消息的 next 指向 msg 的 next。
prevMsg.next = msg.next;
} else {
// 如果 msg 是消息隊(duì)列的第一條消息,則 msg 的 next 作為消息隊(duì)列的第一條消息 // msg 的 next 置空,表示從消息隊(duì)列中取出了 msg。
mMessages = msg.next;
}
msg.next = null; // msg 的 next 置空,表示從消息隊(duì)列中取出了 msg
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse(); // 標(biāo)記 msg 為正在使用
return msg; // 返回該消息,退出循環(huán)
}
} else {
// 如果沒(méi)有消息,則設(shè)置阻塞時(shí)長(zhǎng)為無(wú)限,直到被喚醒
nextPollTimeoutMillis = -1;
}
// 如果消息正在退出,則返回 null
// 正常運(yùn)行的應(yīng)用程序主線(xiàn)程的消息隊(duì)列是不會(huì)退出的,一旦退出則應(yīng)用程序就會(huì)崩潰
if (mQuitting) {
dispose();
return null;
}
// 第一次循環(huán) 且 (消息隊(duì)列為空 或 消息隊(duì)列的第一個(gè)消息的觸發(fā)時(shí)間還沒(méi)有到)時(shí),表示處于空閑狀態(tài)
// 獲取到 IdleHandler 數(shù)量
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// 沒(méi)有 IdleHandler 需要運(yùn)行,循環(huán)并等待
mBlocked = true; // 設(shè)置阻塞狀態(tài)為 true
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// 運(yùn)行 IdleHandler,只有第一次循環(huán)時(shí)才會(huì)運(yùn)行
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // 釋放 IdleHandler 的引用
boolean keep = false;
try {
keep = idler.queueIdle(); // 執(zhí)行 IdleHandler 的方法
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler); // 移除 IdleHandler
}
}
}
// 重置 IdleHandler 的數(shù)量為 0,確保不會(huì)重復(fù)運(yùn)行
// pendingIdleHandlerCount 置為 0 后,上面可以通過(guò) pendingIdleHandlerCount < 0 判斷是否是第一次循環(huán),不是第一次循環(huán)則 pendingIdleHandlerCount 的值不會(huì)變,始終為 0。
pendingIdleHandlerCount = 0;
// 在執(zhí)行 IdleHandler 后,可能有新的消息插入或消息隊(duì)列中的消息到了觸發(fā)時(shí)間,所以將 nextPollTimeoutMillis 置為 0,表示不需要阻塞,重新檢查消息隊(duì)列。
nextPollTimeoutMillis = 0;
}
}
nativePollOnce(ptr, nextPollTimeoutMillis) 是調(diào)用 native 層的方法執(zhí)行阻塞操作,其中 nextPollTimeoutMillis 表示阻塞超時(shí)時(shí)長(zhǎng):
nextPollTimeoutMillis = 0 則不阻塞
nextPollTimeoutMillis = -1 則一直阻塞,除非消息隊(duì)列被喚醒
三、總結(jié)
消息機(jī)制的流程如下:
- 準(zhǔn)備階段:
在子線(xiàn)程調(diào)用 Looper.prepare() 方法或 在主線(xiàn)程調(diào)用 Lopper.prepareMainLooper() 方法創(chuàng)建當(dāng)前線(xiàn)程的 Looper 對(duì)象(主線(xiàn)程中這一步由 Android 系統(tǒng)在應(yīng)用啟動(dòng)時(shí)完成)
在創(chuàng)建 Looper 對(duì)象時(shí)會(huì)創(chuàng)建一個(gè)消息隊(duì)列 MessageQueue
Looper 通過(guò) loop() 方法獲取到當(dāng)前線(xiàn)程的 Looper 并啟動(dòng)循環(huán),從 MessageQueue 不斷提取 Message,若 MessageQueue 沒(méi)有消息,處于阻塞狀態(tài)
- 發(fā)送消息
使用當(dāng)前線(xiàn)程創(chuàng)建的 Handler 在其它線(xiàn)程通過(guò) sendMessage() 發(fā)送 Message 到 MessageQueue
MessageQueue 插入新 Message 并喚醒阻塞
- 獲取消息
重新檢查 MessageQueue 獲取新插入的 Message
Looper 獲取到 Message 后,通過(guò) Message 的 target 即 Handler 調(diào)用 dispatchMessage(Message msg) 方法分發(fā)提取到的 Message,然后回收 Message 并繼續(xù)循環(huán)獲取下一個(gè) Message
Handler 使用 handlerMessage(Message msg) 方法處理 Message
- 阻塞等待
- MessageQueue 沒(méi)有 Message 時(shí),重新進(jìn)入阻塞狀態(tài)