根据 Android 开发者文档,Handler
的主要用途有两个:
Message
和Runnable
对象在将来的某个时刻计划执行。注:以下源码基于 Android 11.0 (R)
Handler
Handler
的原型如下所示:
package android.os;
public class Handler {
final Looper mLooper;
final MessageQueue mQueue;
final Callback mCallback;
final boolean mAsynchronous; // TODO
...
}
可以看出,Handler
有几个重要属性,包括一个Looper
、一个消息队列、一个Callback
等。Callback
是Handler
的内部接口:
Handler.java:
public interface Callback {
boolean handleMessage(@NonNull Message msg);
}
可以看出,Callback
接口的作用在于,若用其对Handler
进行初始化则不必自己去实现Handler
的子类。接收Callback
作为参数的Handler
构造函数有Handler(Looper, Callback)
。
Looper
Looper
是为线程运行消息循环的类。默认情况下,线程没有与之关联的Looper
;要创建一个的话,在将运行循环的线程中调用Looper.prepare()
,然后使用Looper.loop()
使其处理消息,直到循环停止为止。原型如下:
package android.os;
public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); // TODO
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
...
}
可以看出,Looper
同样有一个消息队列。其实Handler
中的消息队列都是通过mQueue = mLooper.mQueue
来赋值的,也就是说,其只是引用Looper
里的消息队列而已。初始化Looper
时会新建一个消息队列:
Looper.java:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
这个消息队列可以通过常规的getQueue()
获得,也可通过Looper.myQueue()
获得,不同的是,后者是静态方法,获取的是当前线程的消息队列:
Looper.java:
public static @NonNull MessageQueue myQueue() {
return myLooper().mQueue;
}
记录在Looper
的线程可用于判断当前线程与Looper
所绑定的线程是否是同一个:
Looper.java:
public boolean isCurrentThread() {
return Thread.currentThread() == mThread;
}
MessageQueue
MessageQueue
是包含要由Looper
调度的消息列表的低级类。消息不是直接添加到MessageQueue
,而是通过与Looper
关联的Handler
对象添加。原型如下:
package android.os;
public final class MessageQueue {
private final boolean mQuitAllowed; // TODO
private long mPtr; // used by native code // TODO
Message mMessages; // TODO
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>(); // TODO
private IdleHandler[] mPendingIdleHandlers; // TODO
private boolean mQuitting; // TODO
...
}
可以看出,消息队列里的消息,既不是通过数组也不是通过队列来保存的,当然这里也不可能是一个消息队列只有一条消息,所以继续看Message
的实现。新建一个消息队列时,需要传入quitAllowed
参数,以表明该消息队列是否可退出:
MessageQueue.java:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}
Message
Message
定义一条消息,其中包含可以发送给Handler
的描述和任意数据对象。原型如下:
package android.os;
public final class Message implements Parcelable {
public int what; // TODO
public int arg1; // TODO
public int arg2; // TODO
public Object obj; // TODO
public Messenger replyTo; // TODO
/*package*/ int flags; // TODO
/** @hide */ public long when; // TODO
/*package*/ Bundle data; // TODO
/*package*/ Handler target; // TODO
/*package*/ Runnable callback; // TODO
/*package*/ Message next; // TODO
/** @hide */ public static final Object sPoolSync = new Object(); // TODO
private static Message sPool; // TODO
private static int sPoolSize = 0; // TODO
private static final int MAX_POOL_SIZE = 50; // TODO
private static boolean gCheckRecycle = true; // TODO
public Message() {
}
...
}
可以看出,Message
里有一个指向next
的Message
,所以Message
不仅可以代表一条消息,也可以代表消息链上的一个节点。也就是说,消息队列是通过链表的形式来存储消息的,它只保管一个头部消息节点。
好了,对这几个类有一个大致的认识后,我们再来看看Handler
该怎么用。首先,要用得创建一个Handler
:
Handler.java:
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
/** @hide */
public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
除了创建上述普通的Handler
之外,还可以创建异步Handler
。创建异步Handler
时,只是将mAsynchronous
属性标记为true
。异步Handler
的作用,下文会进行阐述。
Handler.java:
public static Handler createAsync(@NonNull Looper looper) {
if (looper == null) throw new NullPointerException("looper must not be null");
return new Handler(looper, null, true);
}
public static Handler createAsync(@NonNull Looper looper, @NonNull Callback callback) {
if (looper == null) throw new NullPointerException("looper must not be null");
if (callback == null) throw new NullPointerException("callback must not be null");
return new Handler(looper, callback, true);
}
从 Android 11.0 开始,官方不再推荐使用Handler()
以及Handler(Callback)
,也就是说必须明确传入Looper
,原因见官方解释:Handler | Android Developers。这里可以通过Looper.getMainLooper()
传入主线程的Looper
,或者通过Looper.myLooper()
传入当前线程的Looper
。Looper.getMainLooper()
以及Looper.myLooper()
的定义如下:
Looper.java:
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
myLooper()
方法返回的是与当前线程绑定的Looper
对象,没有绑定则返回空。以上只是获取Looper
的方法,所以为了能获取到Looper
对象,需要先执行Looper.prepare()
方法进行创建。调用该方法生成的Looper
,其消息队列可退出。
Looper.java:
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.prepare()
会将一个新的Looper
对象存放在ThreadLocal
当中,从而使该Looper
与线程绑定。因此在子线程新建Handler
时,需要先执行Looper.prepare()
,如果是在主线程中新建Handler
则无需执行,因为系统会自行调用Looper.prepareMainLooper()
方法,该方法同样会调用prepare
方法为主线程新建一个Looper
,但其消息队列不可退出:
Looper.java:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
Looper
与线程绑定的过程涉及到一个泛型类ThreadLocal<T>
,此类提供线程本地变量。该类的原型如下:
package java.lang;
public class ThreadLocal<T> {
public ThreadLocal() {
}
}
可见,ThreadLocal
并没有存储线程本地变量的属性。接下来先看该类的get()
和set()
方法,如下:
ThreadLocal.java:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
可见获取时,ThreadLocal
先从线程中获取其本地变量映射ThreadLocalMap
,然后再根据自身获取对应的映射值。ThreadLocalMap
是ThreadLocal
的内部类,作用相当于保存多组从ThreadLocal
至Object
的映射。(// TODO 具体介绍暂略)
若要用Handler
发送消息,则需要先准备一条消息。虽然Message
的构造函数是公共的,但获取Message
的最佳方法是调用Message.obtain()
或Handler.obtainMessage
的方法之一。这将从回收对象池中拉取,即如果消息池不为空,则可以从消息池中取出消息复用,如果消息池为空则直接创建新消息。Handler.obtainMessage
方法的实现都是直接转换成相对应的Message.obtain
方法。而带参数的Message.obtain
方法都会通过Message.obtain()
来获得一个Message
,然后再填入参数。
Message.java
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.java:
public void setAsynchronous(boolean async) {
if (async) {
flags |= FLAG_ASYNCHRONOUS;
} else {
flags &= ~FLAG_ASYNCHRONOUS;
}
}
而消息屏障是一种特殊的消息,它的Handler target
属性为空。MessageQueue
的postSyncBarrier
方法会新建一个消息屏障并以当前时间为执行时间插入队列中,生成一个token
存储在arg1
属性中并返回。而MessageQueue
的removeSyncBarrier
方法会根据传入的token
来移除对应的消息屏障。不过这两个方法都标记为@hide
,在此暂不细讲。
使用Handler
发送消息,可调用如下方法:
Handler.java:
public final boolean sendEmptyMessage(int what);
public final boolean sendEmptyMessageDelayed(int what, long delayMillis);
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis);
public final boolean sendMessage(@NonNull Message msg);
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis);
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis);
public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg);
send
方法的返回值表示消息是否已成功放入消息队列,返回false
通常是因为处理消息队列的Looper
正在退出。sendEmptyMessage
方法会获取一个Message
并填充what
参数,最终调用相应的sendMessage
方法。而sendMessage
方法最终会调用enqueueMessage
方法:
Handler.java:
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
其中,uptimeMillis
指执行时间。sendMessage
的执行时间是SystemClock.uptimeMillis()
,即自系统启动以来的毫秒数,sendMessageDelayed
的执行时间是SystemClock.uptimeMillis() + delayMillis
,sendMessageAtFrontOfQueue
的执行时间是0
。另外,如果该Handler
是一个异步Handler
,即mAsynchronous
属性为true
,则入队的所有消息都会设置成异步消息。Handler
的enqueueMessage
方法最终调用MessageQueue
的enqueueMessage
方法:
MessageQueue.java:(有删减)
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
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.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;
}
分析上述源码可以得知,入队是根据消息的执行时间来决定消息的位置的。如果执行时间比第一个消息还要早,则将消息插至队头,而且如果当前队列阻塞,则唤醒该队列。否则遍历消息链表,寻找合适位置插入该消息。
除了使用Handler
发送消息外,如果Message
的Handler target
属性不为空,也可以调用message.sendToTarget()
方法。该方法的实现也很简单:
public void sendToTarget() {
target.sendMessage(this);
}
Handler
除了可以发送消息,通过调用各种post
方法还可以发送Runnable
对象。各种post
方法会直接调用相应的sendMessage
方法,其中postAtTime
和postDelayed
可以添加一个Object token
参数,作为移除时的参考标记。由于sendMessage
方法需要一个Message
,post
方法会调用getPostMessage(Runnable)
或者getPostMessage(Runnable, Object)
来生成Message
:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
private static Message getPostMessage(Runnable r, Object token) {
Message m = Message.obtain();
m.obj = token;
m.callback = r;
return m;
}
Handler
还可以移除已经发送的消息,通过以下remove
方法:
public final void removeCallbacks(@NonNull Runnable r);
public final void removeCallbacks(@NonNull Runnable r, @Nullable Object token);
public final void removeMessages(int what);
public final void removeMessages(int what, @Nullable Object object);
public final void removeCallbacksAndMessages(@Nullable Object token);
所有remove
方法均直接交给消息队列的相应方法处理,消息队列移除消息的具体逻辑在此不作赘述。
Handler
也可以检查消息队列里是否有某个消息,通过以下has
方法:
public final boolean hasMessages(int what);
public final boolean hasMessages(int what, @Nullable Object object);
public final boolean hasCallbacks(@NonNull Runnable r);
所有has
方法均直接交给消息队列进行检查,具体逻辑不赘述。
上文提到,一般使用Looper.prepare()
来新建Looper
并绑定到当前线程。执行完Looper.prepare()
之后就可以调用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;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
可以看出,loop()
方法会执行无限循环,每次处理消息队列里的下一条消息,直到队列退出。如果下一条消息未到执行时间,则队列会阻塞。消息队列获取下一条消息的简化逻辑如下:
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>();
private IdleHandler[] mPendingIdleHandlers;
Message next() {
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
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;
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 = idler.queueIdle();
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;
}
}
消息队列在获取消息时,如果下一条是消息屏障,则只会循环取出队列中的异步消息,否则在一般情况下按队列顺序取出消息。如果下一条消息未到执行时间,则计算出需要等待的时间nextPollTimeoutMillis
,在下一个循环时调用nativePollOnce
进行阻塞。如果下一条消息可用,则返回该消息。除了获取消息,next
方法似乎还干了点别的事情。我们先来看一下这里涉及到的IdleHandler
,它是消息队列的内部接口:
/**
* Callback interface for discovering when a thread is going to block
* waiting for more messages.
*/
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
public void removeIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.remove(handler);
}
}
public boolean isIdle() {
synchronized (this) {
final long now = SystemClock.uptimeMillis();
return mMessages == null || now < mMessages.when;
}
}
IdleHandler
的作用在于,当消息队列空闲时,包括队列为空或者消息未到执行时间时,可以先执行一些简单的操作。这些操作放在queueIdle
方法里,该方法返回true
则意味着从mIdleHandlers
移除IdleHandler
,返回false
则保留。
若从消息队列里获取到下一条消息,则会给Handler
去分发,处理完之后会回收该消息。Handler
的分发逻辑如下:
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
public void handleMessage(@NonNull Message msg) {
}
分发消息时,如果消息的Runnable callback
属性不为空,则说明该消息包含的是一个可运行对象,从而直接运行该对象。否则会先检查是否有实现Callback
接口,有则回调该接口,没有就调用Handler
的handleMessage
方法。handleMessage
方法是一个空方法,需要子类去实现。消息处理完就回收:
private static final int MAX_POOL_SIZE = 50;
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 = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
回收方法会清空消息的所有数据,然后将这个空消息放进消息池。消息池里的消息会在调用obtain()
时复用,从而可以避免分配新的消息对象。消息除了被动地回收,你也可以主动去调用回收:
private static boolean gCheckRecycle = true;
public void recycle() {
if (isInUse()) {
if (gCheckRecycle) {
throw new IllegalStateException("This message cannot be recycled because it "
+ "is still in use.");
}
return;
}
recycleUnchecked();
}
当不再需要消息循环时,需要调用quit()
来终止循环:
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
消息循环的退出方法交给了消息队列去完成:
private boolean mQuitting;
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p != null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages = null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p != null) {
if (p.when > now) {
removeAllMessagesLocked();
} else {
Message n;
for (;;) {
n = p.next;
if (n == null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next = null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
} while (n != null);
}
}
}
可以看出,普通的退出就是将消息队列里的消息全部回收,安全退出就是只回收执行时间在当前时间之后的所有消息。之所以需要安全地退出,是因为队列里的消息可能已经到了执行时间,只是还没轮询到,退出时会把这部分消息都留着。
至此,一个消息从获得、发送、入队到出队、分发、处理、回收的流程就结束了。