這是按我的讀代碼的順序寫的。也可參考下面的連結。
Hander的初始化:
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*/
public Handler() {
this(null, false);
}
/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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) == ) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//首次獲得Looper,而此時的mLooper中已經有MessageQueue,因為//myLooper方法中就一行代碼,即sThreadLocal.get(),說明//sThreadLocal中儲存有一個Looper的引用。那麼具體什麼時候new Looper的呢?
// 如果讀到這個地方不明白,可以查找下看下ActivityThread.java檔案中的main()方法。
//就是在該方法中調用了Looper.prepareMainLooer()方法,完成了消息隊列的初始化。
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//通過mLooper獲得mQueue;mQueue就是消息隊列,定義時類型為final MessageQueue mQueue;
mQueue = mLooper.mQueue;
//此時callback為空
mCallback = callback;
//标記位為異步還是同步,傳入參數為false,說明是同步
mAsynchronous = async;
}
handler的發送消息和處理消息
總結,發送消息就是将message放入從Loope中擷取的消息隊列中。(handler 中儲存的MessageQueue也是從Looper中擷取的,參看代碼中文注釋)
發送消息
/**
* Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
//首先在目前時間之前等待消息,之後将一個消息放入到消息隊列的尾部。在目前線程關聯的handler中,該消息會被handleMessage接受。
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, );
}
//接下來調用這個方法:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < ) {
delayMillis = ;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
/**
* Enqueue a message into the message queue after all pending messages
* before the absolute time (in milliseconds) <var>uptimeMillis</var>.
* <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
* Time spent in deep sleep will add an additional delay to execution.
* You will receive it in {@link #handleMessage}, in the thread attached
* to this handler.
*
* @param uptimeMillis The absolute time at which the message should be
* delivered, using the
* {@link android.os.SystemClock#uptimeMillis} time-base.
*
* @return Returns true if the message was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the message will be processed -- if
* the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
//在絕對時間之前,所有的推送消息之後,将該消息放入消息隊列
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;
}
//放入消息隊列,queue就是mQueue.handle構造時候從Looper.myQueue中擷取到的。
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);
}
處理消息
處理消息這塊分了兩塊:
1. 有一個Callback接口,裡面有一個handlerMessage方法
2. Handler類内部有一個handlerMessage方法
//先看第一個,代碼很簡單,主要看注釋。
/**
* 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
*/
//當執行個體化一個Handler,可以使用該接口,為了避免不得不執行個體化自己的handler子類。
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
* Subclasses must implement this to receive messages.
*/
//子類必須實作這個方法,去接受消息并更新UI。
public void handleMessage(Message msg) {
}
消息是從哪來的?
看消息分發
/**
* Handle system messages here.
*/
//在這裡處理系統消息
public void dispatchMessage(Message msg) {
//如果消息自帶callback接口,調用handleCallback()方法。
//否則,判斷目前的mCallback是否為空null,不為空,使用目前的mCallback,來處理這個消息,否則使用handler對象的handlerMessage方法處理消息。mCallback初始化在handler的構造方法中,通常使用的是null。是以通常情況下消息的處理都是handlerMessage.
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
這裡也産生了一個問題是通常handle對象調用dispatchMessage方法,而用戶端編寫的時候并沒有調用此方法,那是哪個類調用該方法,而且和用戶端都持有的是同一個對象?應該是Looper調用的,繼續找。
Looper
構造方法:
//完成new消息隊列,和擷取目前線程的引用
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
//其實prepare方法就是new Looper();就是new MessageQueue.
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");
}
//new Looper,并儲存到sThreadLocal中
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//擷取子線程的Looper對象me
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//擷取Looper中的MessageQueue
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
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 != && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//調用handler進行消息分發,在handler的dispathchMessage中有調用了handleMessage方法。此時就構成了一個循環。
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != ) {
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();
}
}
prepare方法,就保證了一個線程隻能建立一個Looper對象(特指子線程)
主線程使用的prepareMainLooper()方法,進行建立。
總結:首先在主線程(ActivityThread.java 中的main方法中)當中建立一個Handler對象,并重寫handleMessage()方法。然後當子線程中需要進行UI操作時,就建立一個Message對象,并通過Handler将這個消息發送出去。之後這條消息就會被添加到MessageQueue的隊列中等待被處理,而Looper則會一直嘗試從MessageQueue中取出處理的消息,最後分發會Handler的handleMessage()方法中。由于Handler是在主線程中建立的,是以此時handlerMessage()方法中的代碼也會在主線程中運作,于是我們就可以友善的進行UI操作。
補充:其實,在Activity啟動的時候,在ActivityThread類中的main方法中就建立了消息隊列,并維護了一個Looper.loop()的循環。
參考文獻:
—《第一行代碼》
— Android中為什麼主線程不會因為Looper.loop()方法造成阻塞,非常值得一看。