概述
Android的消息机制主要是指Handler的运行机制以及其关联的MessageQueue和Looper的工作过程,要想弄清楚Android的消息机制,需要弄清楚几个重要类的工作原理:
- ThreadLocal
- MessageQueue
- Looper
- Handler
本篇文章主要从对什么这几个类的分析入手来分析Android的消息机制,代码有点多,纯属个人的学习记录,有错误的地方欢迎指出。
ThreadLocal
ThreadLocal是一个线程内部的数据存储类,用于在指定线程中存储数据,数据存储后,只有在指定的线程中才可以获取到存储的数据。虽然在不同的数据中访问的是同一个ThreadLocal对象,但是获取到的值却不一样。具体工作原理可自行研究,这里不做展开。
MessageQueue
MessageQueue有两个重要的操作:消息的插入和读取。插入对应的方法为enqueueMessage,作用是往消息队列中插入一条 消息;读取对应的方法为next,作用是从消息队列中读取一条消息并将其从队列中删除。从代码上来看,MessageQueue虽然叫消息队列,但是其内部实现却是通过单链表的数据结构来维护消息列表的,因为单链表在插入和删除上效率有优势。
下面来看enqueueMessage和next方法的实现:
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 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;
}
}
从next的方法实现可以看到内部有一个无限循环,当有新消息到来时,next方法会返回该消息并将其从单链表中删除;若没有消息时,next方法会阻塞
Looper
- Looper是一个在线程中运行消息循环的类,线程默认是没有关联消息循环的,使用Looper可以达到这个目的 。
- 使用过程:在要运行消息循环的线程里面执行prepare方法,然后再执行loop方法来开启消息循环,而消息循环的处理一般交给Handler类
- 一个典型的例子:
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();
}
}
Looper里面定义的变量不多,其中主要的
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
先看其构造方法,构造参数quitAllowed会直接传给MessageQueue,这个参数的作用后面会涉及到
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
接着看一个重要的方法:prepare方法
/** 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()}.
*/
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));
}
从代码看到,prepare创建了一个可终止的Looper,并放到了sThreadLocal里面,了解过ThreadLocal的应该知道这是一个跟线程相关的类;prepare方法默认创建了一个可以终止的Looper,那什么时候会创建不可终止的Looper呢?往下可以看到
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
/**
* 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();
}
可见prepareMainLooper方法会创建一个不可终止的Looper,可以查到在ActivityThread的main方法里面调用了该方法,由此可见,这个方法就是为主线程创建Looper的,并且只能保证同时有且只有一个,由于主线程贯穿app的整个生命周期,所以这里声明为不可终止的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 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 {
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();
}
}
loop方法的工作过程是一个死循环,唯一退出循环的方式就是MessageQueue的next方法返回了null,当Looper的quit方法被调用时,就会调用MessageQueue的quit方法或quitSafely方法来通知消息队列退出,当消息队列被标记为退出时,其next方法就会返回null。
Looper必须退出,不然会一直无限循环下去,Looper调用了MessagQueue的next方法来获取消息,而next方法是一个阻塞操作,当没有消息的时候就会阻塞,从而导致Looper阻塞。
如果MessagQueue的next方法返回了新消息时,Looper就会处理:msg.target.dispatchMessage(msg);这里的msg.target是发送这条消息的Handler对象,这样Handler发送的小组最终又交给它的dispatchMessage方法来处理。需要注意的是这里的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这样就成功的将代码逻辑切换到指定的线程中执行了。
quit退出方法的代码如下
/**
* Quits the looper.
* <p>
* Causes the {@link #loop} method to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @see #quitSafely
*/
public void quit() {
mQueue.quit(false);
}
/**
* Quits the looper safely.
* <p>
* Causes the {@link #loop} method to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* However pending delayed messages with due times in the future will not be
* delivered before the loop terminates.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p>
*/
public void quitSafely() {
mQueue.quit(true);
}
Handler
Handler的主要工作是发送和接收消息。发送消息主要是通过send或是post方法,实际上post方法最终也是使用了send方法,代码实现如下:
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);
}
可见,send方法只是调用MessageQueue的enqueueMessage方法把消息插入到消息队列中。而MessageQueue的next方法会把该消息返回给Looper,而Looper最终会通过调用Handler的dispatchMessage方法把消息交给Handler处理,如下:
/**
* 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);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
由代码可知,Handler处理消息的过程如下:
首先判断Message的callback是否为null,若不为null,则通过handleCallback来处理消息。Message的callback是一个Runnable对象,实际上就是通过Handler的post方法传递的Runnable参数,handleCallback会直接调用callback的run方法。
若callback为null,则会判断mCallback是否为 null,不为null则会直接调用其handleMessage方法来处理,mCallback为一个接口定义如下:
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public boolean handleMessage(Message msg);
}
可以知道,Callback可以用来创建一个Hander 实例而不需要派生Handler的子类,是一直Handler的简化使用。
最后如果mCallback为空,则会调用Handler的handleMessage方法来处理消息。
整个流程可以用以下流程图来表示:
概括
- 整个消息机制主要由以下几部分组成:
- 消息队列MessageQueue
- 消息循环Looper
- 消息处理Handler
- 消息载体Message
- 整体工作过程用图表示如下
问题
- 系统为什么不允许在子线程中访问UI呢?这是因为Android的U控件不是线程安全的,如果在多线程中并发访问会导致UI控件的状态不可预期
- 为什么不给UI控件的访问加锁机制呢?首先加锁机制会降低UI访问的效率,因为锁机制会阻塞某些线程的执行;其次锁机制也会令逻辑变得复杂。