1、概述
相信大家对Handler的使用再熟悉不过了,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();
}
}
当我们在主线程或者在其它线程获取到LooperThread线程中的mHandler实例并调用mHandler.sendMessage()时,消息会传递到LooperThread线程中并在handleMessage方法中执行对消息的特定处理。不知道大家有没有想过为什么在一个线程发送消息另一个目标线程能够正确接收并做相应处理?这篇文章就带领大家从源码的角度一步步理解Android的消息机制。Android的事件处理是基于消息循环的,Android的消息机制离不开Looper、MessageQueue、Handler,其实理解Android的消息机制就是理解以上三者的作用与联系。
2、Looper
我们先来看看官方文档对Looper的解释
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
从中我们可以知道,Looper是一个线程的消息循环器,线程默认是没有消息循环器的。我们可以通过prepare方法为一个线程创建消息循环器,然后通过调用loop方法处理消息直至循环终止。我们看看调用prepare方法后都发生了什么:
public final class Looper {
private static final String TAG = "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;
private Printer mLogging;
/** 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方法中首先会通过调用ThreadLocal的get方法判断当前线程的消息循环器Looper是否为空,为空则通过Looper构造器创建实例,否则抛出异常。从异常信息我们可以知道一个线程只有一个Looper。在这里ThreadLocal的作用是关联线程和Looper,一个线程对应一个Looper,即调用prepare方法的线程会和prepare方法创建的Looper实例关联,且一个线程和唯一一个Looper关联,当第二次调用prepare方法时程序会抛出异常。接下来我们看看通过Looper构造方法实例化对象时发生了什么:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
从源码我们能够看到实例化Looper时,会初始化消息队列MessageQueue(MessageQueue后续会详解)以及记录当前Looper关联的线程。MessageQueue作为Looper的成员变量在此时也与Looper建立了关联。接下来我们看看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
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();
}
}
从以上源码我们不难理解,首先通过myLooper()方法获取当前线程的Looper实例,如果为空则抛出必须先调用prepare方法为当前线程关联Looper的异常信息。接下来进入到loop方法中最重要的部分是一个for(;;)死循环。在循环中Looper关联的消息队列MessageQueue会通过调用next方法获取消息队列中的消息Message,并且循环会把消息分发给相应的目标对象。 msg.target.dispatchMessage(msg);这行代码即是对消息的分发。其中target是Handler实例,即调用sendMessage方法发送的消息所关联的Handler。Handler调用dispatchMessage分发消息最总会调用handleMessage方法这样就进入到了我们对消息的处理流程(后文会对Handler进行详解,这里提到只是为了便于大家理解)。我们看到Message msg = queue.next(); // might block这行源码做了注释,意思是next方法的调用可能会发生阻塞。也就是说当消息队列中有消息时,next方法会返回消息对象否则当前线程会一直阻塞直至队列中有新消息把当前线程唤醒。不知道大家注意到了loop方法的注释没有,Be sure to call * {@link #quit()} to end the loop.我们要调用quit方法结束循环。调用quit方法最终会使得MessageQueue next方法返回null,当为空时会跳出for死循环,这样线程最终才可能结束生命。如果线程在处理完自己的任务后不调用quit方法,线程将一直阻塞或被新的无用消息唤醒而最终无法终止,这无疑是对资源的浪费。
至此,Looper的源码分析完了,当然有一些方法并没有分析(请大家自行阅读),现在我们对Looper做一个总结:一个线程唯一对应一个Looper,一个Looper唯一关联一个消息队列MessageQueue。Looper不断从消息队列中取出消息并分发给目标对象。还有要注意的是线程处理完相应任务后要调用quit方法结束循环,否则会造成不必要的资源浪费。
2、MessageQueue
接下来我们继续分析MessageQueue,首先我们还是看官方文档的解释
/**
* 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.
*
* <p>You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/
官方文档解释的很清楚,MessageQueue持有待分发的消息列表。我们通常不会直接操作MessageQueue插入消息而是通过Handler。我们可以通过Looper类的方法myQueue获得当前线程的MessageQueue。MessageQueue最重要的两个作用是消息入队和消息出队。首先我们来看看入队方法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;
}
我们能够看到前面几行代码对消息状态进行了判断,包括如果消息分发的目标对象为空或者消息已经被使用将抛出异常,以及如果终止了消息循环,消息将不会插入到队列中并且返回false。接下来是消息入队的核心代码,可以看到是典型的链表结构:如果表头为空则创建表头,否则将数据插入到表的末尾。通过分析代码我们也能够知道,虽然MessageQueue字面意思是消息队列,但它真正的内部数据结构并不是队列而是普通链表。接下来我们继续看出队方法next的源码,我们截取其中比较重要的一部分
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;
}
从代码中我们不难看出消息出队其实就是链表表头的向下移动,每次从消息队列中取出一个消息,就返回表头指向的Message实例,并且表头向下移动一位。上文我们提到了用Looper 的quit方法终止消息循环,其实最终调用的是MessageQueue的quit方法。quit方法有个safe参数,表示是否安全终止循环。所谓安全是当调用quit方法后消息队列中无法插入新的消息,但是循环可能不会立即终止,直至消息队列中待分发的消息(如果有)分发完毕。不安全的终止与之相反,消息循环会立即终止,新的消息也无法插入。至此,MessageQueue的主要方法分析完毕了,其它的一些方法如removeMessage、quit等请大家自行阅读分析,下面我们队MessageQueue做一个总结:MessagQueue的作用主要是存储消息,并且对外提供一些接口对消息操作如插入消息、取出消息、移除消息等。
网友评论