Android 消息機制主要指 Handler 的運行機制战授,包括了 MessageQueue掰读、Looper 和 Handler 的共同作用。其中 MessageQueue 以隊列的形式對外提供插入和刪除,它內(nèi)部由單鏈表實現(xiàn)裁赠。Looper 的作用是處理 MessageQueue 中存儲的消息。
通常赴精,Handler 被我們用來更新 UI贮喧,有如下兩種常見的用法
public class MainActivity extends AppCompactActivity implements View.OnClickListener {
...
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
// 進(jìn)行 UI 操作
}
};
...
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
...
handler.sendMessage(message);
}
}).start();
}
}
或者
public class MainActivity extends AppCompactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
// 進(jìn)行 UI 操作
}
});
}
}).start();
}
}
用法一
在子線程完成耗時操作后巍膘,通過 sendMessage 方法發(fā)送消息,回到 Handler 所在的主線程,通過 handleMessage 方法完成 UI 操作许饿。
來看 sendMessage 和它的后續(xù)方法
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);
}
可以看到,經(jīng)過這幾個方法宽档,發(fā)送的消息最終都傳入了 MessageQueue 的 enqueueMessage 方法中图谷,于是我們找到 enqueueMessage 方法
boolean enqueueMessage(Message msg, long when) {
...
synchronized (this) {
...
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;
}
在 enqueueMessage 方法中,它主要執(zhí)行的是單鏈表的插入操作逐哈,并沒有對消息隊列里的消息執(zhí)行芬迄,那執(zhí)行操作在哪呢?開頭說到 Looper 的作用是執(zhí)行 MessageQueue 中的消息昂秃,于是找到 Looper 的 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)杜窄,它會調(diào)用 MessageQueue 的 next 方法來獲取新消息,當(dāng) next 方法返回空時會退出循環(huán)算途。來看 next 方法源碼
Message next() {
...
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) {
// Stalled by a barrier.
// Find the next asynchronous message in the queue.
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 (false) Log.v("MessageQueue", "Returning message: " + msg);
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
...
}
...
}
}
next 方法用 mMessage 管理消息隊列塞耕。當(dāng)消息隊列不為空時,返回并刪除當(dāng)前消息嘴瓤,并將下一條消息置前扫外。若消息隊列為空,next 方法會一直阻塞廓脆,直到有新消息到來筛谚。那 next 方法何時返回空呢?當(dāng) Looper 的 quit 方法調(diào)用時狞贱,next 會返回空刻获。因為當(dāng) Looper 調(diào)用 quit 方法,MessageQueue 的 quit 或 quitSafely 方法會被調(diào)用瞎嬉,此時消息隊列會被標(biāo)記為退出狀態(tài)蝎毡,next 判斷到消息隊列的狀態(tài)便會返回空。
接著看 loop 方法氧枣,如果 next 方法返回了消息沐兵,它會調(diào)用msg.target.dispatchMessage(msg)
來處理,其中msg.target
就是發(fā)送消息的 Handler 對象便监。也就是說通過 sendMessage 方法發(fā)送的消息會來到 Handler 對象的 dispatchMessage 方法扎谎,來看 dispatchMessage 方法
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
dispatchMessage 方法會檢查 Message 的 callback 是否為空,不為空就通過 handleCallback 方法來處理消息烧董。Message 的 callback 是一個 Runnable 對象毁靶,它實際上就是 post 方法傳來的 Runnable 參數(shù)。在 handleCallback 方法中會執(zhí)行傳來的 Runnable 對象
private static void handleCallback(Message message) {
message.callback.run();
}
接著 dispatchMessage 方法會判斷 mCallback 是否為空逊移,若不為空预吆,調(diào)用 mCallback 的 handleMessage 方法,若為空胳泉,則調(diào)用 Handler 的 handleMessage 方法拐叉。其中 mCallback 的 handleMessage 方法指的是通過 Callback 接口實現(xiàn)的 handleMessage 方法
/**
* 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);
}
就這樣,通過 sendMessage 發(fā)送的消息最終回到了 handleMessage 方法進(jìn)行處理扇商。
用法二
在子線程中通過 post 方法傳入一個 Runnable 對象凤瘦,在該對象中實現(xiàn) UI 操作。
來看 post 方法
public final boolean post(Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
這里使用了 sendMessageDelayed 方法發(fā)送了一條消息案铺。getPostMessage 方法的作用是將 Runnable 對象轉(zhuǎn)換成一條消息
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
sendMessageDelayed 方法經(jīng)過的流程在上面已經(jīng)分析過蔬芥。最終,通過 post 傳入的 Runnable 對象會來到 dispatchMessage 方法中,被 handleCallback 方法調(diào)用坝茎。
補充
在子線程中直接創(chuàng)建 Handler 會報錯涤姊,正確的用法是
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
在主線程中不必這樣,因為它會調(diào)用Looper.prepareMainLooper
方法來創(chuàng)建 Looper嗤放。
相關(guān)參考 郭霖的博客