[toc]
涉及的類(lèi)主要有這四個(gè)
Message
MessageQueue
Looper
Handler
Message 消息對(duì)象
1、 主要屬性 what obj target 缓艳,主要講講target
target 就是一個(gè)發(fā)送和處理消息是綁定的一個(gè)handler對(duì)象邑蒋,它是在sendMessage時(shí)指定成需要發(fā)送消息的那個(gè)handler, 在Looper.loop()中被調(diào)用去處理消息
MessageQueue 消息隊(duì)列
1、 主要有兩個(gè)方法 enqueueMessage() 入隊(duì) 和 next() 出隊(duì)兩個(gè)方法蜡塌。
enqueueMessage() : 在handler.sendMessage 最終其實(shí)就是調(diào)用的就是MessageQueue.enqueueMessage()古今,你可以理解這個(gè)方法是一個(gè)消息鏈表添加一個(gè)message對(duì)象.那它是什么時(shí)候回創(chuàng)建的呢蠕搜?
//handler.sendMessage 最終其實(shí)就是調(diào)用的就是MessageQueue.enqueueMessage()
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this; //上面說(shuō)的指定了target
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//queue 是什么時(shí)候創(chuàng)建的轮蜕?看Handler構(gòu)造方法
return queue.enqueueMessage(msg, uptimeMillis);
}
//Handler 構(gòu)造方法
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; // 在創(chuàng)建handler的時(shí)候就指定了MseeageQueue對(duì)象的實(shí)例昨悼,從這里也可以知道MessageQueue實(shí)例是在Looper對(duì)象里面。
mCallback = callback;
mAsynchronous = async;
}
截止目前跃洛,還是沒(méi)有回答上一個(gè)問(wèn)題率触,什么時(shí)候創(chuàng)建的queue。我們繼續(xù)看下一個(gè)對(duì)象Looper
Looper 消息泵
這個(gè)對(duì)象其實(shí)就是一個(gè)消息泵汇竭,不停的在處理消息葱蝗。我們需要關(guān)心的兩個(gè)方法 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 內(nèi)部使用了一個(gè)類(lèi)似于map來(lái)維護(hù)
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到這個(gè)Only one Looper may be created per thread 细燎,一個(gè)線(xiàn)程只能創(chuàng)建一個(gè)looper 两曼,然后調(diào)用了sThreadLocal.set(new Looper(quitAllowed)) 在Looper對(duì)象的構(gòu)造方法中,就會(huì)創(chuàng)建一個(gè)Messagequeue對(duì)象
2玻驻、Looper.loop()
這個(gè)是loop()方法的全部?jī)?nèi)容
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 (;;) { // 無(wú)限for循環(huán)悼凑,不停的獲取消息,調(diào)用target對(duì)象身上的dispatchMessage
//出隊(duì)獲取到消息對(duì)象
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對(duì)象璧瞬,調(diào)用它的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時(shí)彪蓬,從來(lái)沒(méi)有創(chuàng)建過(guò)Looper.prepare方法寸莫,那么looper對(duì)象實(shí)例是什么時(shí)候被創(chuàng)建的呢捺萌?
其實(shí)在創(chuàng)建UI線(xiàn)程(ActivityThread )時(shí)档冬,就已經(jīng)創(chuàng)建了Looper對(duì)象
public static void main(String[] args) {
/...
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper(); //內(nèi)部調(diào)用了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的工作機(jī)制了桃纯,sendMessage發(fā)送消息酷誓,其實(shí)就是一個(gè)入隊(duì)操作,而dispatchMessage就是處理消息态坦,我們通常的handleMessage就是在這里被調(diào)用的盐数。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
截止目前我們可以大概理解Handler消息機(jī)制大概是這樣的:
在UI線(xiàn)程被創(chuàng)建時(shí),ActivityThread 的main方法就會(huì)創(chuàng)建一個(gè)Looper對(duì)象伞梯,并啟動(dòng)消息泵Looper.loop()玫氢,并創(chuàng)建一個(gè)MessageQueue對(duì)象,在我們創(chuàng)建Handler的時(shí)候谜诫,獲取到Looper對(duì)象和它身上的queue對(duì)象漾峡,并在Handler.sendMessage()方法調(diào)用mQueue對(duì)象的入隊(duì)方法。Looper.loop()內(nèi)部維護(hù)這一個(gè)無(wú)限for循環(huán)喻旷,不斷的從queue.next() 方法生逸,獲取到Messge對(duì)象并調(diào)用msg.target.dispatchMessage(msg)處理消息。