版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:[http://www.lxweimin.com/p/69a04c5d5fc1)
要想說清楚Handler消息機制原理,先得搞清楚消息機制中的幾個類,以及它們的關系
public class Handler
public final class Looper
public final class MessageQueue
public final class Message implements Parcelable
先說說Looper類,它有一個靜態變量sThreadLocal和myLooper()的靜態函數
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
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));
}
sThreadLocal對象為線程局部對象,簡單來說通過它的get函數每個不同的線程都會獲取到唯一的對象為T類型的變量,這里面T的類型為Looper類型,所以每個Thread里面通過sThreadLocal的get函數都能獲取到唯一的Looper變量。ThreadLocal的原理是什么,就是根據ThreadLocalMap進行保存值,而ThreadLocalMap對象又保存在Thread中。
言規正傳,通過以上的分析我們知道了Looper調用myLooper()就是獲取到當前Thread的Looper對象(在第一次調用myLooper()之前需要先調用prepare())。
Looper類里面有一個類型為MessageQueue的成員變量mQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在講MessageQueue之前,先說說Message,Message也是我們常用的,經常通過obtain獲取Message
public final class Message implements Parcelable {
public int what;
public int arg1;
public int arg2;
public Object obj;
public Messenger replyTo;
public int sendingUid = -1;
/*package*/ long when;
/*package*/ Bundle data;
/*package*/ Handler target;
/*package*/ Runnable callback;
// sometimes we store linked lists of these things
/*package*/ Message next;
}
Message中有一個重要的指向下一個Message的next引用。這就很像數據結構中的單鏈表的節點。實際上Message存儲在MessageQueue中就是以單鏈表的形式保存的,同時也是有序的。以Message中的long when的大小進行從小到大排序。
同時還要一個Handler target對象,表示該消息最終由哪個Handler處理。
現在來說MessageQueue,MessageQueue中有兩個重要的函數enqueueMessage()和next(),enqueueMessage是向消息隊列中插入一條消息,以when的大小進行從小到大的有序插入。
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.
//如果mMessages消息為空,或者when為0或者when小于mMessages的when,插入在表頭
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;
//否則找到一個時間大于when的Message的前面插入
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;
}
很簡單,以when為大小,有序插入到mMessages為表頭的鏈表中。
next()函數就更簡單了,取出mMessages表頭中的消息,如果當前時間小于表頭Message時間,則先等待msg.when-currentTime時間,然后取出表頭消息。
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;
}
nextPollTimeoutMillis = 0;
}
}
如其名MessageQueue就是一個消息隊列的數據結構,里面有插入,查詢,刪除等操作。
那么又是誰在使用MessageQueue呢,當時是Handler了。我們經常用到的Handler里的sendMessage最終就是調用MessageQueue的enqueueMessage函數,向隊列中插入一條消息。
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;//注意這句,將發送消息的Handler賦值給Message對象,在Looper循環的時候就能找到對應的Handler處理消息
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler中的mQueue對象是一個MessageQueue類型,它是誰賦值的呢
final Looper mLooper;
final MessageQueue mQueue;
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;
}
可以看到它引用的是Looper里面的mQueue。
這里我們可以總結下,一個Thread里面只有一個Looper,主線程的Looper就是sMainLooper。每個Looper里面有一個MessageQueue。一個Thread里面Handler可以有很多個實例對象,可以new很多個。但是它們最終指向的Looper對象只會有一個,MessageQueue也只會有一個。所有通過Handler發送的消息,最終都是插入到當前Thread對應的Looper中的MessageQueue中,且以時間進行排序。
那么最后來看看Looper的消息循環
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 (;;) {
//調用MessageQueue的next()函數獲取到Message
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;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//然后將msg丟給msg里面的Handler對象進行處理。
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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里面就很簡單了,調用MessageQueue的next()函數獲取到Message,然后將msg丟給msg里面的Handler對象進行處理。這樣消息就最終回到了Handler處理,我們來看看Handler的dispatchMessage
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果Handler的mCallback不為空先調用mCallback處理,返回true,直接return
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
/**
* Subclasses must implement this to receive messages.
*這就是new Handler的時候實現的handleMessage處理消息
*/
public void handleMessage(Message msg) {
}
如果msg的callback不為空,則調用callback處理。否則判斷Handler的mCallback是否能處理,否則調用handleMessage處理消息。
以上就是Handler消息機制,還是比較簡單的。