Android的消息機制指的是Handler、Looper、MessageQueue三者的運行機制,這三個是一體的,缺一不可。下面來介紹下這三者的工作原理。
消息隊列的工作原理
MessageQueue 是以單鏈表的數(shù)據(jù)結(jié)構(gòu)來存儲消息的單元,主要包含兩個操作:插入和讀取,讀取又伴隨著刪除操作。
插入對應(yīng)enqueueMessage()方法,這個方法的作用是往消息隊列中插入一條消息。
讀取對應(yīng)next()方法,這個方法是從MessageQueue中讀取一條消息并將其從消息隊列刪除。如果有新消息,next()方法就會返回這條消息給 Looper 并將其從消息隊列中移除,如果消息隊列中沒有消息,next()就會一直阻塞在那里。
Looper的工作原理
Looper扮演著消息循環(huán)的角色,它會無限循環(huán)的查看MessageQueue中是否有新消息,有新消息就處理,沒有就阻塞。
源碼中 Looper 的構(gòu)造函數(shù):
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在 Looper 的構(gòu)造函數(shù)會創(chuàng)建一個消息隊列,所以Looper和MessageQueue是一對一的關(guān)系。
Looper 的構(gòu)造函數(shù)是private的,不能在外部直接 new,Handler 的運行必須要有 Looper,那么如何創(chuàng)建 Looper 呢?
Looper為我們提供了prepare()方法,源碼如下:
/** 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));
}
prepare的源碼很簡單,先是調(diào)用new Looper(quitAllowed)方法構(gòu)造Looper,然后把這個Looper對象保存到ThreadLocal中,在其他地方可以通過這個ThreadLocal的get方法來取得這個Looper對象。
創(chuàng)建Looper后,再通過loop方法來開啟消息循環(huán),只有調(diào)用了looper方法,消息循環(huán)系統(tǒng)才會起作用。
看下looper方法的源碼:
/**
*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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
}
從loop的源碼可以看出:它是一個死循環(huán),他內(nèi)部調(diào)用的是MessageQueue的next()方法。當(dāng)next()返回新消息,Looper 就會處理此消息:
msg.target.dispatchMessage(msg)
msg.target指得是發(fā)送該消息的 Handler 對象,而dispatchMessage運行在創(chuàng)建 Handler 的 Looper 所在的線程,即消息的處理是在 Looper 所在的線程。
MessageQueue 的 next() 方法沒消息時就會一直阻塞在那里,導(dǎo)致 loop() 方法也一直阻塞在那里,這樣子線程就會一直處于等待狀態(tài)。
我們可以看到注釋里有這么一句話:
Be sure to call {@link #quit()} to end the loop`.
// 要我們確保調(diào)用了 quit() 方法來結(jié)束 loop。
Looper提供了兩個退出循環(huán)的方法:
/**
*Quits the looper.
*/
public void quit() {
mQueue.quit(false);
}
/**
* Quits the looper safely.
*/
public void quitSafely() {
mQueue.quit(true);
}
這兩個方法最終調(diào)用的時 MessageQueue 里的quit()方法,MessageQueue 的 quit() 方法通知消息隊列退出,當(dāng)消息隊列被標(biāo)記為退出狀態(tài)時,next()方法就會返回null,從源碼中可以看到跳出loop循環(huán)的唯一方法是 MessageQueue 的 next() 方法返回null,這樣 Looper 就退出了,線程就會立刻終止。
這兩個方法的區(qū)別是:quit()直接退出,quitSaftely()把消息隊列里的消息都處理完畢后在安全的退出。
Handler的工作原理
Handler通過post的一系列方法發(fā)送Runnable對象,或通過send的一系列方法發(fā)送Message對象,post 方法最終調(diào)用的還是 send 方法:
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
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);
}
由源碼可以看到,使用 post 方法發(fā)送 Runnable 或 send 方法發(fā)送 Message 對象,最終是調(diào)用是 MessageQueue 的 enqueueMessage() 方法向 MessageQueue 中插入消息,所以 post 或 send 系列方法只是向 MessageQueue 中插入一條消息。
MessageQueue 的 next() 方法發(fā)現(xiàn)有新消息,取出來交給 Looper 處理, Looper 又把消息交給 Handler 的 dispatchMessage() 處理,看下 dispatchMessage() 方法:
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
首先是判斷msg.callback,這個 msg.callback 指的時 post 方法所發(fā)送的 Runnable 對象,如果不為 null 就執(zhí)行 handleCallback(msg) 方法,這個方法很簡單,就是執(zhí)行傳入的 Runnable 的 run 方法。
private static void handleCallback(Message message) {
message.callback.run();
}
然后判斷 mCallback ,如果不為 null, 就調(diào)用mCallback.handleMessage(msg)處理消息, mCallback 是個 Handler.Callback 對象,Handler.Callback是個接口:
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
我們可以實現(xiàn)這個接口,然后以Handler handler = new Handler(callback)這種方式來創(chuàng)建 Handler 對象,這個的作用是可以創(chuàng)建一個 Handler 的實例,但不需要派生一個Handler子類并重寫其 handleMessage() 方法。
最后調(diào)用Handler的 handleMessage() 方法,也就是我們在代碼中復(fù)寫的那個 handleMessage() 方法。
Handler還有一個特殊的構(gòu)造方法:
/**
* 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);
}
這個構(gòu)造函數(shù)的作用是創(chuàng)建一個指定Looper的Handler實例。我們可以在子線程中創(chuàng)建一個這樣的實例:
Handler handler = new Handler(Looper.getMainLooper());
Looper.getMainLooper()返回的時主線程的Looper,這樣的Handler可以實現(xiàn)在在子線程中發(fā)送消息,在主線程中處理,因為前面提到過:消息處理是在Looper所在的線程。
總結(jié):
- 線程默認(rèn)是沒有Looper,要使用Handler必須要創(chuàng)建一個Looper
- 主線程,也就是UI線程,被創(chuàng)建時就會初始化Looper,這就是主線程可以不用創(chuàng)建Looper直接使用Handler的原因
- 在Looper的構(gòu)造函數(shù)中會創(chuàng)建對應(yīng)的MessageQueue
- Looper和MessageQueue是一對一的關(guān)系,一個Looper可對應(yīng)多個Handler
- Looper處理消息最終是把消息交給發(fā)送這條消息的Handler處理,Handler的dispatchMessage方法會被調(diào)用
- dispatchMessage方法是在創(chuàng)建Handler時所使用的Looper所在的線程中執(zhí)行的