[toc]
涉及的類主要有這四個
Message
MessageQueue
Looper
Handler
Message 消息對象
1、 主要屬性 what obj target ,主要講講target
target 就是一個發送和處理消息是綁定的一個handler對象,它是在sendMessage時指定成需要發送消息的那個handler, 在Looper.loop()中被調用去處理消息
MessageQueue 消息隊列
1、 主要有兩個方法 enqueueMessage() 入隊 和 next() 出隊兩個方法。
enqueueMessage() : 在handler.sendMessage 最終其實就是調用的就是MessageQueue.enqueueMessage(),你可以理解這個方法是一個消息鏈表添加一個message對象.那它是什么時候回創建的呢?
//handler.sendMessage 最終其實就是調用的就是MessageQueue.enqueueMessage()
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //上面說的指定了target
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//queue 是什么時候創建的?看Handler構造方法
return queue.enqueueMessage(msg, uptimeMillis);
}
//Handler 構造方法
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; // 在創建handler的時候就指定了MseeageQueue對象的實例,從這里也可以知道MessageQueue實例是在Looper對象里面。
mCallback = callback;
mAsynchronous = async;
}
截止目前,還是沒有回答上一個問題,什么時候創建的queue。我們繼續看下一個對象Looper
Looper 消息泵
這個對象其實就是一個消息泵,不停的在處理消息。我們需要關心的兩個方法 Looper.prepare() 和 Looper.loop()
1、Looper.prepare()
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 內部使用了一個類似于map來維護
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到這個Only one Looper may be created per thread ,一個線程只能創建一個looper ,然后調用了sThreadLocal.set(new Looper(quitAllowed)) 在Looper對象的構造方法中,就會創建一個Messagequeue對象
2、Looper.loop()
這個是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 (;;) { // 無限for循環,不停的獲取消息,調用target對象身上的dispatchMessage
//出隊獲取到消息對象
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
// 獲取到綁定在Message消息身上的Handler對象,調用它的dispatchMessage方法,處理消息
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
可能大家還是很疑惑,我們使用handler時,從來沒有創建過Looper.prepare方法,那么looper對象實例是什么時候被創建的呢?
其實在創建UI線程(ActivityThread )時,就已經創建了Looper對象
public static void main(String[] args) {
/...
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper(); //內部調用了Looper.prepare
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
}
4、Handler 消息處理者
截止這里就可以看到Handler的工作機制了,sendMessage發送消息,其實就是一個入隊操作,而dispatchMessage就是處理消息,我們通常的handleMessage就是在這里被調用的。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
截止目前我們可以大概理解Handler消息機制大概是這樣的:
在UI線程被創建時,ActivityThread 的main方法就會創建一個Looper對象,并啟動消息泵Looper.loop(),并創建一個MessageQueue對象,在我們創建Handler的時候,獲取到Looper對象和它身上的queue對象,并在Handler.sendMessage()方法調用mQueue對象的入隊方法。Looper.loop()內部維護這一個無限for循環,不斷的從queue.next() 方法,獲取到Messge對象并調用msg.target.dispatchMessage(msg)處理消息。