前几篇都是写 Binder 系列的文章,Binder 用于跨进程通信。而 Android 中,同一进程的不同线程如何通信呢,就要用到今天的主角 Handler 了。
目录:
- Handler 概念
- 为什么只能通过 Handler 更新 UI
- 子线程使用 Handler
- Handler framework 源码分析
1. Handler 概念
Handler 主要用于异步消息的处理: 有点类似辅助类,封装了消息投递、消息处理等接口。当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分在消息队列中逐一将消息取出,然后对消息进行处理,也就是发送消息和接收消息不是同步的处理。
2. 为什么只能通过 Handler 更新 UI
最根本的目的是解决多线程并发问题:
假设如果在一个 Activity 当中,有多个线程去更新 UI,并且都没有加锁机制,那么会什么样子的问题?更新界面混乱。
如果对更新UI的操作都进行加锁处理的话又会产生什么样子的呢?性能下降。出于对以上问题的考虑,Android 给我们提供了一套更新 UI 的机制,我们只要遵循这个机制就可以了,根本不用去关心多线程并发的问题,所有的更新 UI 的操作,都是在主线程的消息队列中去轮询处理的。
3. 子线程使用 Handler
在子线程中使用 Handler 就意味着 Handler 的实例是在子线程中去创建的。
new Thread(new Runnable() {
public void run() {
Looper.prepare();
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
}
};
handler.sendEmptyMessage(1);
Looper.loop();
};
}).start();
- 在调用之前必须调用 Looper.prepare() 方法,这个是在当前线程中创建一个 Looper。
- Looper.loop() 这个方法是无限循环的,所以在 Looper.loop() 后边的代码是无法执行到的。loop() 方法的主要作用是一直不断的通过 queue.next() 方法来读取来自 messagequeue 中的 msg,这个方法是 block 的状态,如果 queue 中没有消息的话会一直阻塞在这里。
- 关于 Looper 还有一个方法,当我们需要获取 Looper 实例时,可以直接在对应线程调用 Looper looper = Looper.myLooper() 来获取,默认情况下,系统只会给 MainThread 分配一个 looper。
还有一种方式是:获取主线程的 looper,或者说是 UI 线程的 looper。
new Thread(new Runnable() {
public void run() {
// 区别在这,构造 Handler 时,使用的是主线程的 looper
Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "handler msg", Toast.LENGTH_LONG).show();
}
};
handler.sendEmptyMessage(1);
};
}).start();
使用主线程的 looper,然后在子线程中构造 Handler,不需要调用 Looper.prepare() 和 Looper.loop(),因为不需要创建新的 looper。如果在主线程构造 Handler,默认传入的 Looper 对象就是主线程的 looper 对象,它在 ActivityThread 中已经 prepare() 和 loop() 了。
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 启动,下面是 ActivityThread 类的 main():
public static void main(String[] args) {
// 创建主线程的Looper对象, 该Looper是不运行退出,每个进程都有个主线程
Looper.prepareMainLooper();
// ...
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
// 消息循环运行
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
当然 Android 也提供了一个类:HandlerThread,继承于 Thread 类。内部在 run() 方法中已经处理好了 Looper.prepare() 和 Looper.loop()。
4. Handler framework 源码分析
- 4.1 Handler 架构图
- Message:消息分为硬件产生的消息 (如按钮、触摸) 和软件生成的消息;
- MessageQueue:消息队列的主要功能向消息池投递消息 (MessageQueue.enqueueMessage) 和取走消息池的消息(MessageQueue.next);
- Handler:消息辅助类,主要功能向消息池发送各种消息事件 (Handler.sendMessage) 和处理相应消息事件(Handler.handleMessage);
- Looper:不断循环执行 (Looper.loop),按分发机制将消息分发给目标处理者。
- 4.2 Looper
Looper 的 prepare() 方法,无参的表示当前 Looper 不运行退出,而带参的则表示运行退出。Looper.prepare() 在每个线程只允许执行一次,该方法会创建 Looper 对象,Looper 的构造方法中会创建一个 MessageQueue 对象,再将 Looper 对象保存到当前线程的 Thread Local:
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();
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
另外,与 prepare() 相近功能的,还有一个 prepareMainLooper() 方法,该方法主要在 ActivityThread 类中使用。对应的有 getMainLooper(),返回当前应用的 main looper:
public static void prepareMainLooper() {
// 设置不允许退出的 Looper
prepare(false);
synchronized (Looper.class) {
// 将当前的 Looper 保存为主 Looper,每个线程只允许执行一次
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
loop() 进入循环模式,不断重复下面的操作,直到没有消息时退出循环。读取 MessageQueue 的下一条 Message,把 Message 分发给相应的 target;再把分发后的 Message 回收到消息池,以便重复利用:
public static void loop() {
// 获取当前 looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
// 获取 looper 对象持有的消息队列
final MessageQueue queue = me.mQueue;
// 无限循环,从消息队列中取消息
for (;;) {
// 没有消息时会阻塞,除非调用了队列的 quit() 方法,则会返回 null
Message msg = queue.next();
// 队列 quit,退出循环
if (msg == null) {
return;
}
try {
// 每个消息都有一个 target (Handler 对象),交给这个 target 去处理消息
msg.target.dispatchMessage(msg);
} finally {
}
// 回收消息到消息池
msg.recycleUnchecked();
}
}
Looper.quit() 方法的实现最终调用的是 MessageQueue.quit() 方法:
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
MessageQueue 的 quit 方法:
void quit(boolean safe) {
// 当mQuitAllowed为false,表示不运行退出,强行调用quit()会抛出异常
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) { //防止多次执行退出操作
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked(); //移除尚未触发的所有消息
} else {
removeAllMessagesLocked(); //移除所有的消息
}
//mQuitting=false,那么认定为 mPtr != 0
nativeWake(mPtr);
}
}
- 4.3 Handler
对于 Handler 的无参构造方法,默认采用当前线程 ThreadLocal 中的 Looper 对象,并且 callback 回调方法为 null,且消息为同步处理方式。只要执行的 Looper.prepare() 方法,那么便可以获取有效的 Looper 对象。Handler 类在构造方法中,可指定 Looper,Callback 回调方法以及消息的处理方式 (同步或异步),对于无参的 handler,默认是当前线程的 Looper:
public Handler() {
this(null, false);
}
public Handler(Callback callback) {
this(callback, false);
}
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback) {
this(looper, callback, false);
}
public Handler(boolean async) {
this(null, async);
}
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
// 必须先执行Looper.prepare(),才能获取Looper对象,否则为null.
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;
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public interface Callback {
public boolean handleMessage(Message msg);
}
在 Looper.loop() 中,当发现有消息时,调用消息的目标 handler,执行 dispatchMessage() 方法来分发消息:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
// 当Message存在回调方法,回调msg.callback.run()方法;
handleCallback(msg);
} else {
if (mCallback != null) {
//当Handler存在Callback成员变量时,回调方法handleMessage();
if (mCallback.handleMessage(msg)) {
return;
}
}
//Handler自身的回调方法handleMessage()
handleMessage(msg);
}
}
可以发现所有的发消息方式,最终都是调用 MessageQueue.enqueueMessage():
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);
}
public final boolean postAtFrontOfQueue(Runnable r)
{
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageAtTime(msg, uptimeMillis);
}
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);
}
移除消息则是将消息从队列中移除:
public final void removeMessages(int what) {
mQueue.removeMessages(this, what, null);
}
public final void removeMessages(int what, Object object) {
mQueue.removeMessages(this, what, object);
}
- 4.4 MessageQueue
MessageQueue 是消息机制的 Java 层和 native 层的连接纽带,大部分核心方法都交给 native 层来处理,其中MessageQueue 类中涉及的 native 方法如下:
private native static long nativeInit(); private native static void nativeDestroy(long ptr); private native void nativePollOnce(long ptr, int timeoutMillis); /*non-static for callbacks*/ private native static void nativeWake(long ptr); private native static boolean nativeIsPolling(long ptr); private native static void nativeSetFileDescriptorEvents(long ptr, int fd, int events);
MessageQueue 的构造器,MessageQueue 是使用链表结构来存储数据的:
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
//通过native方法初始化消息队列,其中mPtr是供native代码使用
mPtr = nativeInit();
}
提取下一条 message,nativePollOnce 是阻塞操作,其中 nextPollTimeoutMillis 代表下一个消息到来前,还需要等待的时长;当nextPollTimeoutMillis = -1 时, 表示消息队列中无消息,会一直等待下去。当处于空闲时,往往会执行 IdleHandler 中的方法。当 nativePollOnce() 返回后,next() 从 mMessages 中提取一个消息:
Message next() {
final long ptr = mPtr;
if (ptr == 0) { //当消息循环已经退出,则直接返回
return null;
}
int pendingIdleHandlerCount = -1; // 循环迭代的首次为-1
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//阻塞操作,当等待nextPollTimeoutMillis时长,或者消息队列被唤醒,都会返回
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
//当消息Handler为空时,查询MessageQueue中的下一条异步消息msg,则退出循环。
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//当异步消息触发时间大于当前时间,则设置下一次轮询的超时时长
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// 获取一条消息,并返回
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
//设置消息的使用状态,即flags |= FLAG_IN_USE
msg.markInUse();
return msg; //成功地获取MessageQueue中的下一条即将要执行的消息
}
} else {
//没有消息
nextPollTimeoutMillis = -1;
}
//消息正在退出,返回null
if (mQuitting) {
dispose();
return null;
}
//当消息队列为空,或者是消息队列的第一个消息时
if (pendingIdleHandlerCount < 0 && (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
//没有idle handlers 需要运行,则循环并等待。
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
//只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; //去掉handler的引用
boolean keep = false;
try {
keep = idler.queueIdle(); //idle时执行的方法
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
//重置idle handler个数为0,以保证不会再次重复运行
pendingIdleHandlerCount = 0;
//当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.
nextPollTimeoutMillis = 0;
}
}
添加一条消息到消息队列,MessageQueue 是按照 Message 触发时间的先后顺序排列的,队头的消息是将要最早触发的消息。当有消息需要加入消息队列时,会从队列头开始遍历,直到找到消息应该插入的合适位置,以保证所有消息的时间顺序:
boolean enqueueMessage(Message msg, long when) {
// 每一个普通Message必须有一个target
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) { //正在退出时,回收msg,加入到消息池
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
//p为null(代表MessageQueue没有消息) 或者msg的触发时间是队列中最早的, 则进入该该分支
msg.next = p;
mMessages = msg;
needWake = mBlocked; //当阻塞时需要唤醒
} else {
//将消息按时间顺序插入到MessageQueue。一般地,不需要唤醒事件队列,除非
//消息队头存在barrier,并且同时Message是队列中最早的异步消息。
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;
prev.next = msg;
}
//消息没有退出,我们认为此时mPtr != 0
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
移除消息的方法,采用了两个 while 循环,第一个循环是从队头开始,移除符合条件的消息,第二个循环是从头部移除完连续的满足条件的消息之后,再从队列后面继续查询是否有满足条件的消息需要被移除:
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
//从消息队列的头部开始,移除所有符合条件的消息
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
//移除剩余的符合要求的消息
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
- 4.5 Message
每个消息用 Message 表示,Message 主要包含以下内容:
数据类型 成员变量 解释
- int what 消息类别
- long when 消息触发时间
- int arg1 参数1
- int arg2 参数2
- Object obj 消息内容
- Handler target 消息响应方
- Runnable callback 回调方法
创建消息的过程,就是填充消息的上述内容的一项或多项。
消息池,消息池也是链表结构:
在代码中,可能经常看到 recycle() 方法,咋一看,可能是在做虚拟机的 gc() 相关的工作,其实不然,这是用于把消息加入到消息池的作用。这样的好处是,当消息池不为空时,可以直接从消息池中获取 Message 对象,而不是直接创建,提高效率。静态变量 sPool 的数据类型为 Message,通过 next 成员变量,维护一个消息池;静态变量 MAX_POOL_SIZE 代表消息池的可用大小;消息池的默认大小为 50。消息池常用的操作方法是 obtain() 和 recycle()。
obtain(),从消息池取 Message,都是把消息池表头的 Message 取走,再把表头指向 next:
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null; //从sPool中取出一个Message对象,并消息链表断开
m.flags = 0; // 清除in-use flag
sPoolSize--; //消息池的可用大小进行减1操作
return m;
}
}
return new Message(); // 当消息池为空时,直接创建Message对象
}
recycle(),将 Message 加入到消息池的过程,就是把 Message 加到链表的表头:
public void recycle() {
if (isInUse()) { //判断消息是否正在使用
if (gCheckRecycle) { //Android 5.0以后的版本默认为true,之前的版本默认为false.
throw new IllegalStateException("This message cannot be recycled because it is still in use.");
}
return;
}
recycleUnchecked();
}
//对于不再使用的消息,加入到消息池
void recycleUnchecked() {
//将消息标示位置为IN_USE,并清空消息所有的参数。
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) { //当消息池没有满时,将Message对象加入消息池
next = sPool;
sPool = this;
sPoolSize++; //消息池的可用大小进行加1操作
}
}
}