1.几个概念
Handler,消息发送与处理者
Message,消息
MessageQueue,消息队列
Looper,管理消息队列
2.构造Handler
一般我们都是这样初始化handler的
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
进入handler的源码可以看到其构造函数
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()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
这里主要是获取到looper和messageQueue以便绑定,mCallback是一个内部接口对象,继承了handleMessage方法,mAsynchronous与postSyncBarrier有关,这里不讨论
Looper.myLooper()用来获取到当前线程的looper对象
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
sThreadLocal是一个ThreadLocal对象,ThreadLocal可以保存各个线程存储的变量
3.Looper的初始化
这里分两种情况讨论
3.1主线程初始化looper
我们在主线程创建handler的时候并没有初始化looper,是因为主线程已经帮我们做好了,在ActivityThread.java的main方法里面
public static void main(String[] args) {
...
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
}
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用于区分主线程和其他线程的消息队列,只有主线程的消息才能更新UI
3.1其他线程初始化looper
在非主线程使用handler要手动初始化looper,即调用looper.prepare(),其中传递的参数为true
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));
}
4.sendMessage
4.1构造message
虽然我们会采用以下方式构造新的message,但是API还是建议使用obtain方法,这样可以达到复用的效果,避免内存占用
Message message = new Message();
Message message1 = Message.obtain();
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
Message有2个重要的成员变量
/*package*/ Handler target;
/*package*/ Runnable callback;
target是最终去处理这条消息的handler,所以一个线程是允许存在多个handler,message根据target就知道要交给哪个handler去处理了
另外一个就是callback,这是一个runnable对象,如果我们使用postRunnable来发送消息,最终也会生成一个message,并把原来的runnable对象赋值给callback
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
4.2sendmessage
sendMessage或是sendMessageDelayed最后都会走到sendMessageAtTime
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);
}
enqueueMessage会把当前的message放入消息队列,继续到MessageQueue去看
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;
}
这段函数的目的是在消息队列中寻找一个合适的插入点,并完成消息的插入,消息队列实际上是一个链表的结构,先进先出,符合其用途,但是消息队列的顺序是按照消息的执行时间来的,即message.when,所以,即使有一个message很早就进来了,但是其执行时间比较晚,那么,在新的消息被放如消息队列后,原来的消息也会被移动到链表的尾部
需要注意的是,这里面涉及到一个重要的变量mBlocked,如果有一个消息需要延时执行,那么当消息队列中没有其他message需要立即处理的话,消息队列就会被阻塞住,mBlocke=true,这时如果再插入一条message并且需要执行的话就会唤醒消息队列,当然这里的阻塞/唤醒机制涉及到native层的知识,这里不做讨论
5.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;
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;
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
}
...
msg.recycleUnchecked();
}
}
虽然loop函数比较长,但是实际上就是在循环中不断取出message并分发给对应的handler
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;
}
}
需要注意的是,Looper和MeeesageQueue都有for循环的代码块,不同的是Looper用来持续取出message并处理,MeeesageQueue中用来遍历message的链表并返回message对象,Looper中的是死循环,而MeeesageQueue中的不是(链表的长度是一定的)
如果下一个消息需要延时执行,会计算一个nextPollTimeoutMillis,调用nativePollOnce(ptr, nextPollTimeoutMillis)阻塞当前的消息队列,nativePollOnce会走到native层,借助了linux的epoll机制,到时后会自动唤醒
正常情况message没有延时执行的话就会返回链表头部的message
6.主线程Looper中的死循环为什么没有导致应用程序卡死崩溃
- 死循环是保证线程持续运行的手段,例如binder
- activity的创建,oncreate,onresume,onstop等生命周期方法都是在ActivityThread中handler+message完成调用的,ActivityThread所在的主线程可以理解为应用进程本身
- 导致主线程卡死是在onCreate/onStart/onResume等函数中执行时间太长
所以,Looper中的死循环是保证程序持续运行的关键,当没有message要处理或者message延时执行时,looper进入阻塞状态,减少CPU资源的占用
(参考源码sdk-25,Android7.1)