一、引言
Android开发中经常需要在子线程和主线程间切换,通常我们会在子线程中做一些耗时的操作,比如网络请求或者I/O操作,当耗时操作完成后可能需要在UI上做一些更新,由于Android开发不能在子线程中操作UI控件(UI控件不是线程安全的),这个时候就需要通过Handler将更新UI的操作切换到主线程中执行。Android的消息机制主要就是指Handler的运行机制,所以,研究Android消息机制,其实就是研究Handler的运行机制。
二、Handler消息发送
Hnadler的工作主要包含消息发送和接收。消息发送可以通过post或者send系列方法来实现,post最终也会执行send方法。Android源码里面Handler消息发送流程如下:
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);
}
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);
}
通过源码可以知道,Handler消息发送过程就是像MessageQueue中插入了一条消息。
三、MessageQueue消息插入
通过分析Hnadler消息发送的源码可以得知,消息发送的结果就是使用enqueueMessage向MessageQueue里面插入了一条消息,Android源码中enqueueMessage方法如下:
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;
}
通过源码可以知道,enqueueMessage就是像Message的单链表里面插入了消息。没有什么特殊的。回到源码中查看类的说明,有这样一段:
Low-level class holding the list of messages to be dispatched by a{@link Looper}. Messages are not added directly to a MessageQueue,but rather through {@link Handler} objects associated with the Looper.
里面提到另一个对象,Looper。
三、Looper交互
通过上面的分析可以知道,Hnadler消息发送会将消息插入到MessageQueu中,MessageQueue和Looper会有交互。在Looper源码里面有一个关于如何在线程中使用Hnadler的例子:
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
从这个例子可以看出,在线程中使用Hnadler需要先调用Looper的prepare方法,看一下这个prepare方法:
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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
最终调用了Looper的构造方法,
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
构造方法里面创建一个MessageQueue,也就是prepare其实是创建了Looper
再看一下loop这个方法:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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
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 {
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();
}
}
从方法说明里面可以看到,这个方法是必须要调用的。这个方法是一个死循环,Looper通过MessageQueue的next方法读取消息,当MessageQueue的next方法返回null的时候才结束循环,如果next返回的消息不为空,就会调用msg.target.dispatchMessage这个方法。
四、MessageQueue消息读取
通过上面的分析可以知道,Looper会调用MessageQueue的next方法读取消息
Message next() {
...
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;
}
....
}
从源码可以知道,next方法返回了从Handler插入到MessageQueue里面的消息。
五、Handler消息接收
在分析Looper的过程可以得知,Looper通过MessageQueue的next方法读取MessageQueue里面插入的消息,读取到消息时,会调用msg.target.dispatchMessage方法,msg是从MessageQueue里面读取的,而MessageQueue里面的消息又是通过Handler插入的,回到Handler的enqueueMessage方法
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
可以看到,msg.target其实就是当前的Handler,看一下dispatchMessage方法
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
最终调用了handleMessage来处理消息。
六、Hnadler消息机制
通过上面的分析可以得知:
MessageQueue(消息队列)通过单链表的数据结构来维护消息列表,主要包含两个操作:插入和读取。插入和读取对应的方法分别为enqueueMessage和next。
Looper在Android的消息机制中扮演者消息循环的角色, 通过死循环不停地从MessageQueue中查看是否有新消息. 如果有新消息就会处理. 否则就一直阻塞在那里。
Handler主要包含消息发送和接收过程. Handler发送消息的过程就是向MessageQueue中插入一条消息,MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后交由Handler处理,Handler的dispatchMessage方法会被调用,这时Handler就进入了消息接收的阶段(handleMessage)。
七、补充
分析Looper源码时,在线程中使用Handler需要先构建Looper,但是我们平时在主线程(UI线程)里面使用Handler时都是直接创建的Handler,并没执行构建Looper的操作。其实主线程也是有构建Looper的,只不过这一步操作是系统替我们做的,可以查看ActivityThread的源码
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
...
}
通过查看ActivityThread的源码可以看到,主线程通过Looper.prepareMainLooper已经自动构建了Looper,所以,主线程里面关于Handler使用方法和上面的分析过程也是统一的。