在日常的开发中,我们常常要把从网络或者IO线程取的数据,使用Handler发送message到主线程的消息队列去更新UI。与Handler配合的还有Looper,以及MessageQueue。
先上个总体流程图:
接下来去分析下面的五个过程
1.消息队列的创建过程
2.消息队列的循环过程
3.消息队列的发送过程
4.消息队列的处理过程
- SyncBarrier | 同步栅栏
1.消息队列的创建过程
App应用程序启动的时候,待进程创建之后,会执行ActivityThread的main()方法,在该方法内执行主线程的消息队列的创建和消息队列的循环过程
public final class ActivityThread{
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Looper.loop();
}
}
1.1 Looper.prepareMainLooper
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static void prepareMainLooper() {
prepare(false); // #1
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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)); // #2
}
首先看下Looper的构造函数的内容,其中创建了一个MessageQueue对象,保存在成员mQueue中。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper类中存有一个ThreadLocal静态对象,当执行sThreadLocal.set(new Looper);时,这样就将Looper对象保存到当前线程中了。
1.2 Looper.prepare中MessageQueue创建的时候又做了那些事情
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
nativeInit方法是native方法,其对应C++实现为如下:
static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
...
return reinterpret_cast<jlong>(nativeMessageQueue);
}
NativeMessageQueue 对象实例化时新建了Looper对象。
NativeMessageQueue::NativeMessageQueue() :
mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
mLooper = Looper::getForThread();
if (mLooper == NULL) {
mLooper = new Looper(false);
Looper::setForThread(mLooper);
}
}
Looper构造方法为: (下面是android 4.0 的源码,android 7.0 的源码有了一些变化,看不懂,总体思想是一样的)
Looper::Looper(){
...
int pipefd[2];
pipe(pipefd); //#1 创建管道
int epfd = epoll_create(intsize); //#2 创建epoll
struct epoll_event eventItem;
memset(& eventItem,0,sizeof(epoll_event)); //#3 给eventItem分配内存
eventItem.events = EPOLLIN; //#4 EPOLLIN 表示对应的文件描述符上有可读数据
eventItem.data.fd = pipefd[0];
result = epoll_ctl(epfd,EPOLL_CTL_ADD,pipefd[0],&eventItem);
}
1.3 epoll机制
epoll机制:可以同时监听多个文件描述符的IO读写事件而设计的。
a. 创建一个epoll实例
int epfd = epoll_create(intsize);
参数 initsize 为epoll实例需要监听的IO读写事件的数目大小。epfd 为epoll实例的文件描述符。
b. 使用epoll来监听某个文件描述符上的事件
int epoll_ctl(int epfd, intop, int fd, struct epoll_event* event);
第一个参数是 epoll_create() 的返回值,
第二个参数 op 表示动作,用三个宏来表示:
EPOLL_CTL_ADD: 注册新的fd到epfd中;
EPOLL_CTL_MOD: 修改已经注册的fd的监听事件;
EPOLL_CTL_DEL: 从epfd中删除一个fd;
第三个参数是需要监听的fd,
第四个参数是告诉内核需要监听什么事件
小结:消息队列的创建过程如下:
- 创建Looper对象,保存到当前线程中
- 创建了MessageQueue对象,MessageQueue在c++层又创建了c++层的Looper对象
- 创建了管道,和epoll实例,让epoll实例监听管道的读文件描述符
2.消息队列的循环过程
消息队列的循环则是通过Looper.loop()方法
public class Looper{
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;
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
}
}
myLooper()方法先取出当前线程的消息队列,然后for循坏不断检查这个消息队列。如果当前线程的消息队列为空,那么queue.next()方法会使线程进入睡眠等待的状态。
2.1 MessageQueue.next()方法
Message next() {
...
int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
for (;;) {
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
//取到从开机到现在的时间
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
// 如果msg.target为空,表示这个msg为同步障碍消息,那么就从Message消息队列遍历,
//直到遍历完,或者取到异步消息为止
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
//当前时间小于msg的执行时间,表示执行时机还不到,计算出差值
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 {
// 拿到该消息返回,并从消息队列中移除
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.
//遍历IdleHandler,依次执行它们
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);
}
}
}
pendingIdleHandlerCount = 0;
//执行过IdleHandler,就需把该值致为0,因为不知道idleHandler中执行的多久
nextPollTimeoutMillis = 0;
}
}
当遍历消息队列时,当没有新的消息需要处理时,并不是马上进入睡眠,而是先调用注册到它的消息队列中IdleHandler对象的成员函数queueIdle,以便它们有机会在线程空闲时执行一些操作。当执行过,执行过IdleHandler,就需把该值致为0,因为不知道idleHandler中执行的多久。
2.2 nativePollOnce(ptr, nextPollTimeoutMillis)
其对应的c++实现为:
static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
jlong ptr, jint timeoutMillis) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}
void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
mPollEnv = env;
mPollObj = pollObj;
mLooper->pollOnce(timeoutMillis);
mPollObj = NULL;
mPollEnv = NULL;
...
}
int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
int result = 0;
for (;;) {
...
if (result != 0) {
return result;
}
result = pollInner(timeoutMillis);
}
}
最终会调用到pollInner(timeoutMills)中
int Looper::pollInner(int timeoutMillis) {
int result = POLL_WAKE;
...
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
//这里调用函数epoll_wait来监听mEpollFd实例,如果该epoll所监听的读文件描述符没有读事件,那么就在timeoutMillis中指定的事件内进入睡眠等待状态。(这个mEpollFd就是我们在创建消息队列的时候,让epoll监听管道的读文件描述符)
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
...
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeEventFd) {
//如果IO读写事件的类型为EPOLLIN
if (epollEvents & EPOLLIN) {
// 从管道中将数据读完
awoken();
}
}
...
// Release lock.
mLock.unlock();
return result;
}
小结:java层调用messageQueue.next()方法时,该方法是一个for循环,循环内部,第一次去去查询时,nextPollTimeoutMillis为0,表明管道中没有数据时,也不睡眠,在回到java层,这里就去遍历Message消息队列了,如果消息队列为空,那么nextPollTimeoutMillis就会被复制为-1,进入无限睡眠等待状态,直到有其他向管道中写数据,被唤醒为止。唤醒之后,在去查询消息队列,有需要执行的msg返回给ActivityThread.loop()方法就处理消息,没有呢就计算睡眠时间,赋值给nextPollTimeoutMillis变量。然后判断是否有IdleHandler的消息需要处理,如果有就进行处理,处理完之后,还在for循环内,继续轮询,并且这里nextPollTimeoutMillis赋值为0,也就是不会睡眠,
3. 消息队列的发送过程
发送消息是通过Handler的方式,继续分析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);
}
看下MessageQueue.enqueueMessage的实现
boolean enqueueMessage(Message msg, long when) {
...
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;
//1. 判断消息队列的队头消息是否为空
// 2. 插入消息的执行时间是否为零,
// 3. 插入消息的执行时间小于队头中的消息执行时间。
// 上面三种情况将消息插入消息队列头部
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
//情况1
needWake = mBlocked;
} else {
//mBlocked 这个bool值表示该Handler对应的目标线程是否处理睡眠状态,为true,表示需要唤醒
//情况2
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
//p == null为遍历完,或者找到位置跳出循环
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;
}
3.2 什么时候需要唤醒目标线程
情况1: 当插到消息队列头部时:如果目标线程是睡眠的,那么就唤醒它
往管道写消息,唤醒目标线程
- 消息队列为空
- 消息的执行时间为0
- 插入消息的执行时间早于队头元素
为上面三种情况时,且目标 线程为睡眠状态时,往管道写数据
情况2:当消息得插入到消息队列的中间时:
另外一种唤醒情况为:
目标线程处于睡眠,消息队列队头为同步栅栏,并且插入的消息为异步消息。(p.target == null,表明当前消息队列的头部为一个同步堵塞消息,且插入的消息是异步消息,目标线程处于睡眠等待状态,将needWake设为true。另外,当遍历消息的时候,发现消息队列已经有异步消息了,那么把needWake设为false。)
总结唤醒条件:往消息队列队头插, 或者在设置了同步栅栏之后,发异步消息给消息队列。(也就是说,往消息队列中间插,这时目标线程处于睡眠状态,那么也不会唤醒,当然这也是没必要的,随着时间流逝,自然会处理到)
3.3 nativeWake(mPter)
static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
nativeMessageQueue->wake();
}
void NativeMessageQueue::wake() {
mLooper->wake();
}
nativeWake唤醒方法是向管道的写文件描述符写入一个“W”字符,这样前面调用epoll_wait的地方就会被唤醒,继续执行。
4.消息队列的处理过程
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;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
msg.target.dispatchMessage(msg);
}
从消息队列中拿到消息后,从msg.target中拿到Handler,然后执行handler.dispatchMessage()
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//当消息有设置callback,则当消息到达时,执行对应callback回调
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//一半会重写handleMessage()
handleMessage(msg);
}
}
使用Handler.post发送消息时
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
初始化Handler时,也可传入callback对象
public Handler(Callback callback) {
this(callback, false);
}
5. Handler的SyncBarrier (同步障碍,栅栏)
同步堵塞的消息是一个特殊的消息,下面代码和普通入消息队列一样,仅仅不同的是其msg.target为空。
public int postSyncBarrier() {
return postSyncBarrier(SystemClock.uptimeMillis());
}
private int postSyncBarrier(long when) {
// Enqueue a new sync barrier token.
// We don't need to wake the queue because the purpose of a barrier is to stall it.
synchronized (this) {
final int token = mNextBarrierToken++;
final Message msg = Message.obtain();
msg.markInUse();
msg.when = when;
msg.arg1 = token;
Message prev = null;
Message p = mMessages;
if (when != 0) {
while (p != null && p.when <= when) {
prev = p;
p = p.next;
}
}
if (prev != null) { // invariant: p == prev.next
msg.next = p;
prev.next = msg;
} else {
msg.next = p;
mMessages = msg;
}
return token;
}
}
5.1 同步栅栏有啥用呢
Message next() {
...
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
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());
}
Looper.loop()方法从MessageQueue取消息时,此时消息队列队头元素msg.target为null,表明队头为栅栏消息,那么它会一直往下遍历消息队列,直到找到异步消息为止。然后在判断该消息的执行时间是否要到了。到了就返回给Looper进行处理。
5.2 在Android系统中的应用
ViewRootImpl{
//View树遍历
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
//此时往MessageQueue塞入一个同步栅栏
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
...
}
}
}
public void postCallback(int callbackType, Runnable action, Object token) {
postCallbackDelayed(callbackType, action, token, 0);
}
public void postCallbackDelayed(int callbackType,
Runnable action, Object token, long delayMillis) {
if (action == null) {
throw new IllegalArgumentException("action must not be null");
}
if (callbackType < 0 || callbackType > CALLBACK_LAST) {
throw new IllegalArgumentException("callbackType is invalid");
}
postCallbackDelayedInternal(callbackType, action, token, delayMillis);
}