如果想要弄懂Android的消息机制,就一定要深入挖掘Handler、MessageQueue和Looper这三者之间的关系。
1.开启消息循环
从一个普通的子线程开启Looper循环讲起:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}).start();
上面的代码我们分三步来研究:
①Looper.prepare()
②new Handler()
③Looper.loop()
①Looper.prepare():
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到,Looper.prepare()最终调用的是自身的构造函数,在构造函数中实例化了一个MessageQueue,并获取了当前的线程。通过将实例化的Looper放在ThreadLocal中,从而实现Looper和线程的绑定。
下面看看new MessageQueue(quitAllowed)做了些什么
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
MessageQueue在构造函数中通过native方法进行了初始化工作。
②new Handler():
public Handler() {
this(null, false);
}
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());
}
}
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;
}
Handler在构造函数中通过Looper.myLooper()
来获取在当前线程中创建的Looper对象(所以在子线程中需要手动写Looper.prepare(),否则mLooper为null会报异常。由于主线程会自动创建smainLooper,所以在主线程中实例化的Handler无需手动创建Looper也不会报异常。关于主线程的消息机制最后会讲到)。此外,还获取了mLooper中的messageQueue对象,并将异步状态设为false。
③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
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 {
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();
}
}
我们可以清晰地看到,loop方法实际是执行的一个死循环。
在该循环中,MessageQueue通过调用next()
来获取Message。
如果msg==null,则跳出该循环(也意味着此消息队列结束);如果msg不为空,则会执行msg.target.dispatchMessage(msg)
。这里的target是发送Message时对应的Handler(后面会讲到为什么),所以这一句代码的功能本质上是调用handler.dispatchMessage(msg),也就是将从MessageQueue中读到的Message通过Handler作分发操作。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
而dispatchMessage就比较容易理解了,通过判断有无callback来选择具体的执行方法。在这里就可以看到我们平时继承Handler最常复写的方法--handleMessage(msg)
。
刚才谈到了Looper.loop()的死循环中会通过MessageQueue的next()方法来获取Message,那么我们再深入去看看这个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);
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;
}
}
可以发现,next()也是个无限循环的方法,如果消息队列中没有消息,则会一直阻塞在这里。只有当msg != null
且now >= msg.when
时才会return msg
。其中now表示当前时间,msg.when表示插入该msg时所指定的期望处理该任务的时间。如果now < msg.when
,表示当前消息还未到执行它的时间,那么就会计算时间差并进行休眠以等待执行时间到来。
此外,mQuitting==true,则会return null,表示关闭该消息队列。
到这里,我们基本上看完了在子线程中开启消息循环的大致流程。系统所做的无非就是实例化一个Looper并将它与当前线程绑定,然后将Handler的实例化对象与Looper进行绑定,再在Looper中无限循环地调用MessageQueue的next()方法来循环的读取Message。如果读到了Message,则会调用该Message所绑定的Handler对象来执行对应的分发和处理操作。
2.发送消息
发送消息抽象的解释就是通过Handler将Message放入MessageQueue中。对于发送消息这个操作,Android SDK为我们提供了多种Message构造以及Handler发送的方式。
Message有两种常用的构造方式:new Message()
和handler.obtainMessage()
。下面贴上源码来比较二者差别。
以下为Handler.java的部分源码
public final Message obtainMessage()
{
return Message.obtain(this);
}
public final Message obtainMessage(int what)
{
return Message.obtain(this, what);
}
public final Message obtainMessage(int what, Object obj)
{
return Message.obtain(this, what, obj);
}
public final Message obtainMessage(int what, int arg1, int arg2)
{
return Message.obtain(this, what, arg1, arg2);
}
public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
{
return Message.obtain(this, what, arg1, arg2, obj);
}
可以看到handler的obtainMessage方法的多个重载主要区别在于给Message添加的参数上的不同,其内部实现还是得进入Message源码中去查看。
private static final Object sPoolSync = new Object();
private static Message sPool;
private static int sPoolSize = 0;
/** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
*/
public Message() {
}
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();
}
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
public static Message obtain(Handler h, int what, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.obj = obj;
return m;
}
public static Message obtain(Handler h, int what, int arg1, int arg2) {
Message m = obtain();
m.target = h;
m.what = what;
m.arg1 = arg1;
m.arg2 = arg2;
return m;
}
public static Message obtain(Handler h, int what,
int arg1, int arg2, Object obj) {
Message m = obtain();
m.target = h;
m.what = what;
m.arg1 = arg1;
m.arg2 = arg2;
m.obj = obj;
return m;
}
可以看到,Message的obtain方法的多个重载,本质上还是通过无参的obtain方法获取Message对象,然后把传入的参数设入其中。
仔细查阅无参obtain方法的实现,我们可以发现这就是简单的单链表取链表头元素的操作。其首先进行了线程同步,即当前只有一个线程可以执行此方法。然后取出sPool这个链表头所指向的Message对象,并将sPool指向链表的下一结点,链表长度计数减一,然后返回刚刚取出的Message对象。只有当前sPool即链表头为null时才执行new Message()方法来构造Message对象。
那么问题来了,既然Message是以链表的形式存取的,那也应该在某处对应着插入链表的操作才对。仔细想想一个Message会在什么时候回收并插入链表中呢?一定是在Message被处理完之后。那么我们再回过头去看看Looper的loop方法。
public static void loop() {
省略部分代码
for (;;) {
!!从MessageQueue中取Message!!
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
省略部分代码
try {
!!调用Handler处理Message!!
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
}
省略部分代码
!!回收Message!!
msg.recycleUnchecked();
}
}
可以看到,通过msg.target.dispatchMessage(msg)
完成了对Message的处理,随后便调用了msg.recycleUnchecked()
来对Message进行回收操作。
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = -1;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
不难看出,回收操作中先是清除Message中各类参数的信息,随后依然是通过sPoolSync
这个锁进行线程同步,最后便是将当前Message对象的next指向链表头sPool,再将sPool指向当前对象,最后链表长度计数加一,即完成了一次单链表头插的操作。
小总结
正如Message构造函数上所提到的,更倾向于通过obtain方法来获取一个Message对象而不是主动去实例化一个Message对象。因为Android程序是基于事件驱动的,事件的发送是一个高频操作。无论是系统的消息,还是自己发送的消息,如果每次都实例化一个新的Message对象,这无疑会对内存会构成较大的压力。所以Message才会采用单链表的形式在每次使用完之后进行回收,并在使用时从链表中取出来进行复用。
下面我们再看看Handler是如何发送Message的。
Handler发送Message主要有两种方式:sendMessage(Message msg)
h和post(Runnable r)
。
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(Runnable r, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
{
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
//将Runnable转化成Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
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);
}
从上面代码中我们能看到post(Runnable r)
实际上是将Runnable设置给了Message的callback变量,然后走的还是sendMessage
方法。
而sendMessage相关的一系列操作,主要是通过延迟时长delayMillis
和系统当前时间来计算该Message的预计处理时间uptimeMillis
。
随后,在enqueueMessage方法中,我们可以看到msg.target = this;
这样一行代码,这也印证了我们上面提到的Message中的target指的其实就是发送它的Handler。再通过queue.enqueueMessage(msg, uptimeMillis)
方法,将Message插入到MessageQueue中。
接下来我们再看看MessageQueue具体是如何将Message放进消息队列中的。
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;
}
两个关键位置:
①if (p == null || when == 0 || when < p.when)
与这个if判断相关的三个条件分别是消息队列的头节点是否为null;传入的参数when是否为0;传入的参数when是否小于当前消息队列头节点对应的when。三者满足其一就可将传入的msg插入到消息队列的头节点处。
②for (;;)
这个for循环当中执行的遍历链表的操作,当遍历到末尾或者when < p.when
时,便将msg插入到此位置。
看到这儿也顺带解释了一个问题:Message插入MessageQueue是顺序插入的还是基于某些原则插入的?
答:通过比较msg的参数when的大小来插入到MessageQueue的对应位置。
至此,Handler、MessageQueue、Looper三者的关系我们就全部梳理了一遍。
PS:主线程的消息循环
Android的主线程是ActivityThread,其通过在入口main()方法中调用下面几行代码来实现的消息循环:
//省略部分代码
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//省略部分代码
Looper.loop();
//省略部分代码
与子线程相比,区别主要体现在prepareMainLooper和prepare,以及Handler的生产方式不同上。
那么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();
}
}
可以看到,prepareMainLooper其实也是调用的prepare方法,只不过参数为false,表示该线程不允许退出。
主线程上的Handler又有何区别呢?
ActivityThread内部的handler中定义了一组消息类型,主要包含了四大组件的启动和停止等过程。handler接收到消息后会将逻辑切换到主线程去执行,这也就是主线程的消息循环模型。
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
break;
case RELAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
ActivityClientRecord r = (ActivityClientRecord) msg.obj;
handleRelaunchActivity(r);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
break;
case PAUSE_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder) msg.obj, false, (msg.arg1 & 1) != 0, msg.arg2, (msg.arg1 & 2) != 0);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
case PAUSE_ACTIVITY_FINISHING:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder) msg.obj, true, (msg.arg1 & 1) != 0, msg.arg2, (msg.arg1 & 1) != 0);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...........
}
}
主线程上Looper一直无限循环为什么不会造成ANR?
首先我们要明白造成ANR的原因:
①当前的事件没有机会得到处理(即主线程正在处理前一个事件,没有及时的完成或者looper被某种原因阻塞住了)
②当前的事件正在处理,但没有及时完成
Android系统是由事件驱动的,Looper的作用就是在不断的接收事件、处理事件,如Activity的生命周期或是点击事件。Looper的无限循环正是保证了应用能持续运行。如果Looper循环结束,也代表着应用停止。
再回到这个问题,我们可以发现,ANR正是由Looper中那些耗时的事件所造成的,从而导致Looper的消息循环无法正常进行下去。
主线程的死循环一直运行是不是特别消耗CPU资源呢?
其实不然,这里就涉及到Linux pipe/epoll机制,简单说就是在主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,详情见Android消息机制1-Handler(Java层),此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。
参考文献:
《Android开发艺术探索》
《深入理解Android内核设计思想》
https://www.zhihu.com/question/34652589
若您觉得本文章对您有用,请您为我点上一颗小心心以表支持。感谢!