在app启动的时候会去执行ActivityThread.main()方法,在这个方法里面,有Looper.prepareMainLooper()、Looper.loop()方法。其实ActivityThread就是UI线程,Looper.prepareMainLooper()是为UI线程初始化一个Looper和MessageQueue对象,然后Looper.loop()开始进行循环。这样就构成了app的消息循环,以后的启动Activity,view树的绘制都是通过向MessageQueue里面添加消息,然后在Looper.loop()循环里面读取消息,读取到特定的消息后,通过Handler进行处理。具体的代码分析如下:
Looper.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();
}
}
在这段代码里面会去调用prepare(false), prepare方法如下:
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));
}
其中sThreadLocal代表线程变量,一个线程内该变量共享,如果sThreadLocal为空,会将新创建的Looper对象放在sThreadLocal变量里面。Looper的构造函数如下:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();
}
在构造函数里面会去初始化MessageQueue,赋值mThread为当前线程,置mRun标识为true。在执行完prepare()方法后,prepareMainLooper()方法会去执行sMainLooper = myLooper(), myLooper()方法就是去mThreadLocal里面去读Looper对象赋值给sMainLooper,这样初始化完成。
在调用Looper.prepareMainLooper()方法后,系统会帮我们初始化好Looper和MessageQueue对象,并且一个线程只能被调用一次,如果重复调用会抛出异常,所以一个线程对应一个Looper和MessageQueue。
接着初始化完成后,执行Looper.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.recycle();
}
}
整个代码前两句是获取当前的Looper和MessageQueue对象。然后进行到一个for循环,for循环的条件为for(;;), 这是一个死循环。Message msg = queue.next(), 从MessageQueue里面读取消息,如果没有消息会阻塞线程。读取到消息后执行msg.target.dispatchMessage(msg)。msg.target是Handler对象,这个是在Message被构造的时候赋值的,这里会去嗲用Handler.dispatchMessage(msg)方法。具体代码如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
在这里判断msg.callback是否为null, callback是在Message生成的时候赋值的,当通过post(new Runnable() {})这种形式来生成消息的时候,callback就会被赋值,代表Runnable对象。否则callback为null。如果callback不为空时,会去执行message.callback.run()方法。这里的Runnable不会以线程的方式去执行,依旧是在UI线程运行,这个要特别注意!如果callback为null,会去执行handleMessage(Message msg)方法, 该方法就是提供给编程的接口! 执行消息处理代码后,会调用msg.recycle()方法来回收Message对象。这样一个循环就结束了。
接着讲向MessageQueue添加消息以及MessageQueue和Message的内部原理。
首先了解一下Message的内部构成。在Message里面,有几个重要的字段:
public int what;
public Object obj;
Bundle data;
Handler target;
Runnable callback;
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
what、obj、data、target、callback都是Message的一下信息。sPoolSync是异步锁,sPool是一个Message的链表,sPoolSize是这个链表的长度,MAX_POOL_SIZE是链表的最大长度。一般请求Message对象不直接调用Message的构造方法,而是通过调用Message.obtain()方法。这是因为Message内部为我们实现了消息的管理,可以将Message回收,减少内存的消耗。Message.obtain()具体代码如下:
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
sPoolSize--;
return m;
}
}
return new Message();
}
在这里首先对Message加锁,判断sPool是否为空,如果不为空,会将sPool指向的Message对象返回,然后sPool指针指向链表的下一个Message。和他相对应的是Message.recycle()。具体代码如下:
public void recycle() {
clearForRecycle();
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
这个方法里面首先会去调用clearForRecycle(), 这里会去清理Message的那些私有变量。然后在链表的头部加入该Message对象,sPool指针指向自己。这样就节省了开销。
接下来了解向MessageQueue队列添加消息。一般可以通过handler.post或者是Handler.obtainMessage().sendToTarget()来实现。其实内部原理一样,我们挑Handler.obtainMessage().sendToTarget()来了解一下。在Handler.obtainMessage()里面,会去调用Message.obtain(),这个方法我们之前已经说过了。然后调用Message.sendToTarget(), 这个方法会去调用Handler.sendMessage(Message msg)方法。该方法最终会去执行MessageQueue.enqueueMessage()方法,具体代码如下:
boolean enqueueMessage(Message msg, long when) {
if (msg.isInUse()) {
throw new AndroidRuntimeException(msg + " This message is already in use.");
}
if (msg.target == null) {
throw new AndroidRuntimeException("Message must have a target.");
}
synchronized (this) {
if (mQuitting) {
RuntimeException e = new RuntimeException(
msg.target + " sending message to a Handler on a dead thread");
Log.w("MessageQueue", e.getMessage(), e);
return false;
}
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;
}
在MessageQueue里面,Message也是通过链表的形式来组织的。mMessages即为链表的头。根据传递进来的Message的等待时间插入到链表的合适位置,如果当前已经是阻塞状态则会去唤醒线程。具体的唤醒代码是native的。这样就完成了消息循环!