我们首先看下我们的日常使用场景:
下面的例子中我们启动了一个线程在后台上作一些耗时间的操作,在操作结束后通过Handler向主线程发送一个消息更新文本,我们接下来就着这个情景对Handler源代码进行学习。

private Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
if (msg.what == CHANGE_TEXT) {
textView.setText(String.valueOf(msg.obj));
}
super.handleMessage(msg);
}
};
new Thread() {
@Override
public void run() {
try {

//一些耗时的操作
Message msg = Message.obtain();
msg.what = CHANGE_TEXT;
msg.obj = "Hello Handle" ;
handler.sendMessage(msg);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();

首先是调用构造方法创建一个Handler对象,在构造方法的注释中我们看到一个比较有价值的提示:就是如果一个线程没有Looper那么它将不具备接受Message的能力,如果完这种线程中post消息那么将会有异常抛出。

/**
* 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);
}

上面的构造方法实际上是调用了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;
mCallback = callback;
mAsynchronous = async;
}

在这个方法的开始部分会先判断当前的Handler类是否是匿名内部类,或者静态内部类,成员内部类,如果是这些的话需要将Handler声明成static,这个在之前的内存优化的博客中已经提到,如果是非静态的那么将会持有外部类的引用,很有可能造成内存泄露。
紧接着调用

Looper.myLooper()

判断当前线程是否有Looper,这一点我们上面已经提到了如果没有Looper就没有处理消息的能力。那么什么时候才有Looper呢?
我们看下myLooper方法:

/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}

从注释上看我们可以很明显看出它是用于获取当前线程的Looper,那么这个Looper是什么时候设置的呢? 我们接下来看:

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));
}

上面的代码中会先判断当前线程是否已经有Looper了,如果没有那么就添加一个,这就意味着一个线程至多只能有一个Looper。
那么我们上面的代码并没有调用这个prepare方法,为什么没有报错,原因在于主线程在创建的时候就已经随即创建了一个MainLooper,我们看源代码中prepare方法下面的prepareMainLooper方法:

public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}

它会新建一个Looper后将其赋给sMainLooper。

我们可以搜索下这个方法在哪里被调用,我们可以看到AcitivityThread.java中的main方法中有调用该方法:

public static void main(String[] args) {
//.......
Looper.prepareMainLooper();
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();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

在这里主线程创建了一个Looper并添加到sThreadLocal中。

发送Message:
Handler发送消息的方式有很多种我们以最简单的sendMessage(Message msg)来作为分析对象:

public final boolean sendMessage(Message msg){
return sendMessageDelayed(msg, 0);
}

这里会调用sendMessageDelayed(Message msg, long delayMillis)这个方法的第二个参数为延迟时间:

public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}

sendMessageAtTime 会调用enqueueMessage方法将消息入队

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;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
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.
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;
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;
}

从上面代码中可以看出当收到一个Message后将会遍历整个消息队列,并将当前消息插入按照时间排序好的队列中。

那么消息已经进入队列了,那么什么时候被调用的呢?我们在看AcitivityThread.java中的main方法的时候除了prepareMainLooer外在最后调用了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 (;;) {
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

msg.target.dispatchMessage(msg);

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();
}
}

上面的代码其实不难,很容易找到关键代码:

msg.target.dispatchMessage(msg);

msg.target 是什么?其实它就是往MessageQueue中post消息的那个Handler,也就是说Looper会遍历整个消息队列,找到消息的Target然后调用它的dispatchMessage,下面我们来看下dispatchMessage方法,在dispatchMessage方法中调用的是handleMessage这个回调方法,这就是我们写的那个业务逻辑。

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

读到这里可能细心的同学会留意到都没介绍队列中怎么决定某个消息何时处理,是的,这个其实是通过在loop中调用queue.next进行决定的。

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;
}

// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}

if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}

// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler

boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}

if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}

// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;

// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}

这里的代码很长,但是其实关键的逻辑不难,它就是在一段时间内会去编历整个消息队列,查看Message中的when字段,并和当前的时间进行比对,如果达到要发送的时刻那么就返回这个Message给Looper。到此整个Handler源代码学习告一个小段落。我们来回顾下整个过程:

首先在AcitivityThread.java的main方法中会调用Looper.prepareMainLooper();创建一个MainLooper,然后调用Looper.loop();开启消息循环,这时候就可以允许Hanlder往主消息队列投递消息了,我们在主线程中创建Hanlder,在子线程中处理完耗时操作后就可以通过这个Handler完MainLooper中sentMessage,这些消息会通过调用enqueueMessage加入到消息队列中,注意这里的Message持有Handler的引用,这也是为什么需要将匿名内部类,静态内部类的Handler设置为static的原因了,否则Handler会持有外部类的引用,那么只要消息没及时处理,Handler所在的Activity或者Service一旦退出了就会造成内存泄露。
接下来在Looper.looper中会定期查看每个消息,如果时间到了就会调用消息所绑定Handler的dispatchMessage方法。在该方法中调用我们实现的handleMessage。

整个过程如下图所示:

再来站在全局的角度来一张图:

那么子线程可以有处理消息的能力吗,这个问题我们其实在上面已经说过了,默认情况是没有的,因为没有Looper,但是我们可以为一个子线程创建一个Looper这样就有了消息处理的能力了。

class NonMainThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
Contents