1.概述
- Android消息机制主要是指Handler的运行机制
- 更新UI只是Handler的其中一个特殊的使用场景
- 在Android开发中,只允许主线程更新UI(为了保证UI操作是线程安全的)
- 使用Handler机制,在子线程中完成耗时操作后可以切换到主线程更新UI
2.主要成员
Message:
- 线程间通讯的数据单元,存储信息
- Message分为3种:
普通消息(同步消息)
、屏障消息(同步屏障)
、异步消息
- 通常使用的都是普通消息,屏障消息就是为了确保异步消息的优先级,设置了屏障后,只能处理其后的异步消息,同步消息会被挡住,除非撤销屏障
MessageQueue:
- 存储消息、取走消息
- 单链表数据结构存储
- 先进先出,会根据消息执行的时间排序
Handler:
- 发送各种消息到MessageQueue,处理Looper分发过来的消息
- Handler创建时需要当前线程的Looper来构建消息循环系统(从ThreadLocal中获取当前线程的Looper)
Looper:
- 无限消息循环,从MessageQueue中取出消息,并分发给对应的Handler
- 线程默认是没有Looper的,如果需要使用Handler,就必须手动为线程创建Handler * 主线程(ActivityThread)在创建时就已经初始化了Looper
Thread、Looper和Handler之间的数量对应关系
- 1个Thread只能绑定1个Looper,但可以有多个Handler
- 1个Looper可以绑定多个Handler
- 1个Handler只能绑定一个Looper
ThreadLocal:
线程本地存储区(Thread Local Storage,简称为TLS),每个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。Looper类利用了ThreadLocal的特性,保证每个线程只存在一个Looper对象
3.消息机制的运行流程
在子线程中执行完耗时操作后,使用Handler发送消息到MessageQueue,向消息队列中添加消息。然后Looper通过无限轮询,不断从MessageQueue中取出消息,分发给目标Handler处理,这样就切换到了Handler所在的主线程。
4.原理解析
Looper相关:
prepare():初始化一个Looper,并存储到ThreadLocal中:
public static void prepare() {
prepare(true);//默认true,允许退出
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {//Looper类利用了ThreadLocal的特性,保证每个线程只存在一个Looper对象
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
myLooper():在子线程中获取当前线程的Looper,内部是调用了ThreadLocal的get方法:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
getMainLooper():在任意线程获取主线程的Looper:
public static Looper getMainLooper() {
synchronized(Looper.class) {
return sMainLooper;
}
}
loop():无限轮询,不断地从MessageQueue中取出消息,然后交给目标Handler去处理:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
//当前线程必须初始化好Looper
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); //next方法可能会阻塞
if (msg == null) {//消息为空,退出循环
return;
}
...
try {
msg.target.dispatchMessage(msg);//分发Message到目标Handler
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
}
...
msg.recycleUnchecked();
}
}
Handler相关:
构造方法:
public Handler() {
this(null, false);
}
public Handler(@Nullable Callback callback) {
this(callback, false);
}
public Handler(@NonNull Looper looper) {
this(looper, null, false);
}
public Handler(@NonNull Looper looper, @Nullable Callback callback) {
this(looper, callback, false);
}
public Handler(@Nullable Callback callback, boolean async) {
...
mLooper = Looper.myLooper();//从当前线程的TLS中获取Looper对象
if (mLooper == null) {//Looper不能为空
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;//拿到Looper中的MessageQueue
mCallback = callback;//回调
mAsynchronous = async;//设置是否异步处理消息
}
Android中主线程在创建时就已经初始化好了Looper,Handler构造时不传Looper也能直接用:
//ActivityThread的main方法
public static void main(String[] args) {
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
public static void prepareMainLooper() {
prepare(false);//主线程的Looper不允许退出
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
如果想在子线程中创建Handler,必须在Handler创建时传入一个Looper,有以下两种方法:
1.先调用 Looper.prepare() 在当前线程初始化一个 Looper:
Looper.prepare();
Handler handler = new Handler();
// ....
// 这一步可别可少了
Looper.loop();
2.通过构造方法传入Looper:
注:如果是通过这种方式,一定要确保Handler处理消息的语句执行时looper已经准备妥当,可以参考HandlerThread的实现源码
Looper looper = .....;
Handler handler = new Handler(looper);
发送消息方法——send:
public final boolean sendMessage(@NonNull 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(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public final boolean sendMessageAtFrontOfQueue(@NonNull Message msg) {
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, 0);
}
发送消息方法——post:
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean postAtTime(@NonNull Runnable r, long uptimeMillis) {
return sendMessageAtTime(getPostMessage(r), uptimeMillis);
}
public final boolean postAtTime(
@NonNull Runnable r, @Nullable Object token, long uptimeMillis) {
return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
}
public final boolean postDelayed(@NonNull Runnable r, long delayMillis) {
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
/** @hide */
public final boolean postDelayed(Runnable r, int what, long delayMillis) {
return sendMessageDelayed(getPostMessage(r).setWhat(what), delayMillis);
}
public final boolean postDelayed(
@NonNull Runnable r, @Nullable Object token, long delayMillis) {
return sendMessageDelayed(getPostMessage(r, token), delayMillis);
}
public final boolean postAtFrontOfQueue(@NonNull Runnable r) {
return sendMessageAtFrontOfQueue(getPostMessage(r));
}
可以看出,不管是send还是post,最终都是调用了sendMessageAtTime方法:调用MessageQueue的enqueueMessage方法将消息入队:
public boolean sendMessageAtTime(@NonNull 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);
}
send和post的联系和区别:
- 两者本质上是没有区别的,都是发送一个消息到消息队列中,只不过post使用方式更简单
- post会通过getPostMessage方法会将Runnable赋给callback,接下来还是和sendMessage一致的操作,进入sendMessageDelayed:
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
dispatchMessage():处理MessageQueue分发过来的消息:
public void dispatchMessage(Message msg) {
//如果通过post发送消息,则callback不为空,直接进入handleCallback
if (msg.callback != null) {
handleCallback(msg);
} else {
//如果通过send发送消息
if (mCallback != null) {//创建Handler时传进来了Callback
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);//创建Handler时没传Callback(常用)
}
}
//调用Runnable的run方法,并不会启动新线程,所以post的runnable里面可以直接更新UI
private static void handleCallback(Message message) {
message.callback.run();
}
Handler与Looper如何关联?
- 无参构造方法,会从当前线程的ThreadLocal中去取Looper
- 通过构造方法传入Looper
Looper与Thread如何关联?
ThreadLocal(Looper.prepare)
MessageQueue相关:
enqueueMessage():往消息队列中添加一个消息:
boolean enqueueMessage(Message msg, long when) {
//...
//mMessages是消息队列的表头
msg.when = when;
Message p = mMessages;
boolean needWake;
//如果消息链表为空||当前的消息需要立即执行||当前的消息比消息链表头部的消息执行要早
if (p == null || when == 0 || when < p.when) {
// 上面的条件都满足就将消息插入到链表的表头
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
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;
}
//唤醒消息队列去取出消息,分发消息
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
关于Message.when:
- Message.when是一个时间,用于表示 Message期望被分发的时间,该值是
SystemClock.uptimeMillis()
与delayMillis
之和。 -
SystemClock.uptimeMillis()
是一个表示当前时间的一个相对时间,它代表:自系统启动开始从0开始的到调用该方法时相差的毫秒数 -
Message.when
用时间差来表示先后关系
next():在Looper中通过loop()
方法,不断地从MessageQueue获取消息。当队列中消息为空时,则会进行阻塞操作。
Message next() {
...
int pendingIdleHandlerCount = -1;
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
//会阻塞,除非被唤醒(如果有消息被插入到消息队列或者超时时间到)
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//遇到屏障:msg.target == null
if (msg != null && msg.target == null) {
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;
}
...
}
}
next()在没有消息的时候会阻塞,如何恢复?
当其他线程调用enqueueMessage再次插入消息时,就会被唤醒
参考资料:
https://blog.csdn.net/carson_ho/article/details/80175876
https://www.jianshu.com/p/f10cff5b4c25
https://www.jianshu.com/p/f70ee1765a61
https://www.jianshu.com/p/43d6cd7b06f1
http://www.dss886.com/2016/08/17/01/
https://blog.csdn.net/start_m...
https://blog.csdn.net/start_m...