前言
本文主要总结Android消息机制,以及自问自答一道相关面试题。
目录
-
面试题
- Handler.postDelayed()是否精确延时?
1.消息机制概述
-
2.消息机制分析
- ThreadLocal的作用
- 消息队列MessageQueue的工作原理
- Looper的工作原理
- Handler的工作原理
面试题
Handler.postDelayed()是否精确延时?
先给出答案:
当上一个消息存在耗时任务的时候,会占用延时任务执行的时机,当上一个任务耗用总时超过上下任务执行时间的时间差时,后一个任务会被延时,此时是不准确的。如果需要保证任务准时执行,我的理解是,务必将耗时操作放入子线程,任务执行完时,将UI更新部分利用Handler机制切换回主线程,不要利用Handler去实现一些类似于界面动画的工作。
下面是测试代码:
我们可以跟一下postDelayed的源码:
上面的4张图依次是postDelayed的调用路径,可以看到最后由MessageQueue来维持消息队列。再往下即引出我们本文的Android 消息机制分析。
1.消息机制概述
Android 消息机制主要是指是Handler的运行机制以及MessageQueue和Looper的工作过程。
Handler是消息机制的上层接口,作为开发,提到消息机制,我们一定是和Handler打交道。Handler常常被我们用于更新UI,但是本质上Handler并不是只是用来更新UI,它主要的作用是将一个任务切换到Handler所在线程去执行,也可以说是线程间通信。
与Android消息机制相关的还有ThreadLocal类,这是一个线程内部的数据存储类。数据存储后,只有指定线程可以获取,其他线程不可见。
延伸
系统不建议在子线程访问UI的原因:UI控件非线程安全,在多线程中并发访问可能会导致UI控件处于不可预期的状态。
系统不对UI访问加上锁机制主要出于这两点:
- 上锁会让UI访问的逻辑变得复杂
- 上锁会遇到线程阻塞,降低UI访问效率
2.消息机制分析
ThreadLocal的作用
一般来说,当需要以线程为作用域时,我们就需要使用ThreadLocal了,而在Android消息机制中,一个线程只有一个Looper,所以这个时候ThreadLocal很适合用于Local的存取。
查看Looper.prepare();我们就可以看到ThreadLocal的身影,这里如果ThreadLocal已经有Looper对象时,将会抛出异常,每个线程只能创建一个Looper,而为null时,则会实例化一个Looper。
具体关于ThreadLocal的工作原理分析请另外参考文章,Android: 理解Thread的工作原理
消息队列MessageQueue的工作原理
消息队列指的是MessageQueue,主要包括两个操作,插入和读取,分别对应enqueueMessage和next,尽管叫做队列,但内部使用的是一个单向链表。
下方是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; //具体的执行时间在sendMessageDelayed中设置,参考面试题部分的源码分析
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;
}
下面是next的源码,可以发现next是一个无线循环的方法,如果消息队列没有消息,则方法会一直阻塞,有消息来临时,会返回这条消息并且从单列表中删除。
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); //阻塞或者延时到下一个msg执行时间唤醒
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;
}
}
延伸
本文提到的面试题中,假设有2个任务分别为A和B,A延时五秒,B延时2秒,当A插入消息队列后,在next方法中由于还未到执行时间,会重新计算剩余时间,然后继续循环,当B插入时,在执行延时小于当前队列头任务时,会将B任务插入头结点,然后把mBlocked赋值给needWake,调用nativeWake唤起阻塞的Looper。而B任务执行的时间加上延时时间不超过五秒时,Looper会准时提出A消息,从而是一个精确的延时,而相反的,由于当B执行完才会继续调用next方法,所以一旦耗时任务超时,A任务的延时就不再精确,总上,Handler不保时。
Looper的工作原理
Looper在消息机制中主要的职责是不断地从MessageQueue中查看是否还有新消息,有就会处理,否则就会阻塞。在构造Looper对象时,会实例化一个MessageQueue对象,同时持有当前的Thread对象
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
构造Looper主要是通过Looper.prepare()来创建,在上文ThreadLocal部分提到过。
Loop最重要的是loop方法,调用后消息队列开始循环。
/**
* 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();
}
public static void loop() {
final Looper me = myLooper(); //静态方法,从sThreadLocal中获取本线程创建的Looper实例对象
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 (;;) { //无限循环,唯一跳出循环的方式是next返回null时
//queue.next()阻塞时会连带阻塞loop方法
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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//传递给发送消息的handler对象,并且在Looper所在的线程里执行
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
Handler的工作原理
Handler的工作主要包括消息的发送和接收,主要是post和send一系列方法实现,同时post系列方法最后还是调用send方法执行。关于发送部分函数调用过程已经在面试题题解部分提到过,不再赘述。
在实例化Handler的时候会调用Looper.myLooper(),获取到本线程的Looper从而关联上整个消息队列的机制。
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
//主要是获取本线程Looper、消息队列以及传入的callback
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中会调用Message携带的Handler的dispatchMessage方法,这个时候就到了Handler的消息处理阶段:
//使用post传递一个runnable对象时会被包装成一个Message把runnable赋值给msg.callback所以在这里执行对应的runnable
private static void handleCallback(Message message) {
message.callback.run();
}
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
//不派生子类的情况下也就是说new Handler(mCallback)传入的一个接口实例也可以创建Handler
//这里执行的就是这种情况下传入的CallBack
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//派生子类时重写的默认方法
handleMessage(msg);
}
}
至此基本已经分析完了,最后借用一张图,图片来源:android的消息机制——Handler机制