这是按我的读代码的顺序写的。也可参考下面的链接。
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) == 0) {
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, 0);
}
//接下来调用这个方法:
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
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 != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//调用handler进行消息分发,在handler的dispathchMessage中有调用了handleMessage方法。此时就构成了一个循环。
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();
}
}
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()方法造成阻塞,非常值得一看。