平時(shí)用Handler比較多,對(duì)他的內(nèi)部實(shí)現(xiàn)卻不是很了解,只知道Handler用于線程間通訊。最后還是花了一點(diǎn)時(shí)間了解這個(gè)東西。
1、基本概念
Android的消息機(jī)制主要是指:Handler的運(yùn)行機(jī)制、MessageQueue和Looper的工作過程。
平時(shí)使用Handler較多。Handler的主要作用是將一個(gè)任務(wù)切換到某個(gè)指定的線程中去執(zhí)行。比如:子線程中不能直接訪問UI,可以通過Handler將訪問UI的操作切換到主線程中去。
Handler的post傳遞一個(gè)Runnable或者通過send方法發(fā)送一個(gè)Message最后都會(huì)在Looper中處理。
//從源碼中可以看到post和send最后調(diào)用的都是sendMessageDelayed方法。
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);
}
接下來我們看下post方法中的getPostMessage(r)。可以發(fā)現(xiàn)getPostMessage方法中將傳入的Runnable封裝到Message中,傳給Looper的最終都是一個(gè)Message對(duì)象。
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
Looper發(fā)現(xiàn)有新的Message就會(huì)處理這個(gè)Message。最終Handler的dispatchMessage調(diào)用來處理post傳入的Runnable或者send傳入的Message。
最后畫個(gè)圖。

2、消息隊(duì)列的工作原理
消息隊(duì)列在Android中指的是MessageQueue。它負(fù)責(zé)Message單鏈表的維護(hù):Message的添加,讀取刪除操作。
關(guān)鍵的方法:enqueueMessage 、next。
enqueueMessage:往Message隊(duì)列中插入一條Message。
next:從消息隊(duì)列中讀取消息并刪除。
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;
//以下是對(duì)Message單鏈表的添加Message操作
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方法主要是對(duì)Message單鏈接進(jìn)行插入數(shù)據(jù)操作。
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
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;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
從源碼中可以看出,next是一個(gè)無限循環(huán)(for( ; ; ){})的方法,如果消息隊(duì)列中沒有消息,那么next會(huì)一直阻塞。當(dāng)獲取到消息時(shí),next會(huì)返回這條消息并將其從單鏈表中移除。
3、Looper的工作原理
Looper在消息機(jī)制中用于循環(huán)的獲取消息并處理,他會(huì)通過MessageQueue的next方法來獲取新的消息并處理,如果沒有獲取到新的消息則會(huì)阻塞在那里。
關(guān)鍵方法:loop
loop:循環(huán)獲取Message并處理
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方法調(diào)用MessageQueue的next方法獲取新的消息,如果沒有消息next會(huì)阻塞,如果返回了新的消息就會(huì)通過 msg.target.dispatchMessage(msg);處理這條消息。
msg.target就是Handler對(duì)象。也就會(huì)調(diào)用Handler的dispatchMessage方法。
4、Handler的工作原理
Handler主要包含消息的發(fā)送和接收的過程。消息的發(fā)送可以通過post的一系列方法以及send的一系列方法來實(shí)現(xiàn)。
調(diào)用post最終都會(huì)通過send的方法來實(shí)現(xiàn)(基本概念中已經(jīng)提到)。
send最終會(huì)調(diào)用sendMessageAtTime()方法。
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);
}
從源碼中可知queue.enqueueMessage(msg, uptimeMillis)我們可以知道Handler發(fā)送消息的過程是向消息隊(duì)列插入了一條Message。Looper通過MessageQueue的next()獲取到這條消息并處理。最后Looper把消息交給Handler處理(Looper的工作原理中提到的msg.target)。Handler的dispatchMessage方法就會(huì)被調(diào)用。
/**
* 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);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
public void handleMessage(Message msg) {
}
從源碼中我們可以看出。
如果是post一個(gè)Runnable,則會(huì)通過handleCallback方法處理,處理方法為:message.callback.run();
如果是send一個(gè)Message,則會(huì)通過handleMessage方法處理,這里應(yīng)該比較熟悉,重寫handleMessage方法處理Message在開發(fā)中會(huì)經(jīng)常用到。
以上就是Android消息機(jī)制的基本理解??赡艽嬖谌毕?,日后再去補(bǔ)充了。
參考blog:http://www.itdecent.cn/p/d5c9433345e7
http://www.itdecent.cn/p/e266c1490598
參考書籍:安卓開發(fā)藝術(shù)探索