在android中,我们会经常使用到Handler,Message,Looper和MessageQueue,因为它们之间的联系已经被封装好了,所以对于上层来说我们只知道使用Handler,Message就可以了。对于只关注应用开发而言,可以理所当然地这么认为,但是我们最好还是了解下面的运作机制。
首先我们从创建一个HandlerThread开始
在这个过程中我们需要重点了解 thread和looper是怎么绑定的?
一个thread对象只能和一个looper做绑定,在prepare()的时候做的绑定,其实就是把 thread对象和一个looper对象当作 <key,value>放到ThreadLocal (一个类似于map的数据结构) 中,这是一个静态的变量。
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/** 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));
}
然后进入Looper.loop() 循环中,等待事件触发或者超时,jni层的looper用到了epoll ,怎么理解epoll呢?
int Looper::pollInner(int timeoutMillis) {
...
// We are about to idle.
mPolling = true;
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
// No longer idling.
mPolling = false;
...
}
具体的实现讲起来比较复杂,这里只介绍它的作用,上面的流程图中,我们看到loop函数最终会阻塞在pollInner()函数,而这个函数里面最关键的是epoll_wait(),
第一个参数mEpollFd是由epoll_create()创建出来的fd,它可能关联了其他fd,可以把它当作fd集合,第二参数和第三个三个参数不介绍,第四个参数是等待超时的时间,
如果参数是-1就会一直等到mEpollFd可读。所以epoll_wait()的作用就是如果监听的fd集合(mEpollFd)可读(或者有变化)时,就会有返回,否则等待timeoutMillis的时间后返回,如果参数是-1就会一直等待。
接下来我们看一下Handler sendMessage过程
我们先了解一下Handler是怎么和Lopper绑定的吧
前面介绍了,创建HandlerThread,把它run()起来后,就会把thread和looper绑定起来,所以通过HandlerThread就可以拿到绑定的looper对象,如果使用了Handler无参构造函数,那是怎么获取looper对象的呢?
public Handler(Callback callback, boolean async) {
...
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
...
}
/**
* 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();
}
原来是通过sThreadLocal这个静态对象,这里用到了TLS ,不过多介绍,这里的作用就是拿到当前线程绑定的looper对象,如果是在另外的线程创建Handler,那就是拿另外一个线程绑定的looper对象,同理,我们在app的主线程中创建handler对象,用的就是主线程的looper对象。
handler 调用sendMessage后,会把Message插入MessageQueue中,我们重点关注一下新来的message是怎么插入的。
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;
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) {//如果已经到尾部,或者设定的执行时间比新来message的执行时间长,就是要插入的位置
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,Message中的next属性指向下一个message。
if (p == null || when == 0 || when < p.when) 这三个条件分别表示链表中没有Message,或者新来的Message需要马上执行(when == 0),或者新来的Message需要最早执行,则插入链表的头部;否则遍历链表,按照Message设定的执行时间插入到对应的位置。
最后,我们再把Handler.sendMessage() 到Handler.handleMessage() 的过程叙述一遍。
首先Handler会把Message插入到MessageQueue中
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Message的target被设置成发送此Message的Handler对象,Message插入MessageQueue后,queue.next()会取出接下来要处理的Message,如果delay时间是0,epoll_wait()基本马上就返回,所以就从链表中取出了要处理的Message(放在链表头部的message)。
/**
* 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();
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); // might block
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
}
}
取出要处理的Message后,会调用到 msg.target.dispatchMessage(); 这个target就是上面发送Message的Handler对象,如果没有处理Message的callback,就交给Handler.handleMessage()函数处理。
/**
* 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);
}
}
到此,这个流程分析完毕。