前言
Adnroid的消息机制主要是指Handler的运行机制。本次主要分析Android消息机制,主要分析包括Handler、MessageQueue、Looper等实现原理。
1、Handler是什么?
Handler是为了在工作线程中更新UI线程的机制,也是消息处理机制,包括消息的发送和消息的处理过程。
2、为什么要用Handler消息传递机制?
a.为什么Android系统不允许工作线程更新UI?
1、因为ui控件不是线程安全的,多线程中并发访问可能会导致ui控件处于不可预期状态。
2、如果对ui控件进行上锁机制,则会使ui空间操作变得复杂低效。也可能出现阻塞进程的执行。
-
3、采用单线程模型处理ui,不用关心多线程问题,都在ui线程的消息队列中轮询处理。
访问UI只能在主线程中进行。若在工作线程中访问UI就会抛出异常。在Adnroid源码frameworks/base/core/java/android/view/ViewRootImpl.java中的checkThread()来检查。
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
3、Handler工作原理分四个步骤:
- 1、通信准备
- 2、消息发送
- 3、消息循环
- 4、消息处理
1、通信准备
在主线程中创建操作对象,Handler对象,消息循环Looper对象,消息队列MessageQueue对象,且都属于主线程。Handler自动绑定了主线程的Looper、MessageQueue。Hnadler负责发送消息,Looper负责接收消息,并把消息回传给handler中。
public Handler(Callback callback, boolean async) {
// 省略代码...
// 获取对应线程的Looper对象
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
// 获取Looper内部包含的MessageQueue对象
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
2、消息发送
在工作线程中,通过Handler发送消息到消息队列MessageQueue中。Handler类中常用的几个发送消息方法。
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
// 获取一个消息对象
Message m = Message.obtain();
//此处传递的Runnable只是作为普通的callback处理使用
m.callback = r;
return m;
}
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){
//获取当前Handler所在的消息队列
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);
}
//最终调用enqueueMessage方法,调用MessageQueue中的enqueueMessage方法添加消息
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
//消息入队 入参:msg 消息 when 延迟时间
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
// 判断消息对应的Handler是否空
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;
// p 为空直接赋值, 或者消息优先处理,则直接放入队列头部。
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 {
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;
}
消息发送中获取Message的方式:
// 从全局池返回一个新消息实例。允许我们在许多情况下避免分配新对象。如果通过new方式创建,则会出现大量的Message对象,导致频繁的gc,消耗性能。
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
//sPool 为一个Message对象,Message使用的是链表的方式存储
// m 取出消息链表的头部
Message m = sPool;
// sPool指向下一条消息
sPool = m.next;
m.next = null;
m.flags = 0; // 清空 in-use flag
sPoolSize--;
//返回从池中获取到的消息
return m;
}
}
// 池为空则创建一个消息返回
return new Message();
}
Message消息在回收的时候添加到消息链表中:
Message采用了类似享元设计模式,通过享元模式创建一个大小为50的消息池,避免重复创建Message对象。
//将Message对象回收到消息池中
public void recycle() {
//省略代码 ...
// 清空消息状态,并添加到消息池中。
recycleUnchecked();
}
void recycleUnchecked() {
// 设置标识位flags ,该flags会在obtain()中置0
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) {
//池的大小小于MAX_POOL_SIZE,则将next消息添加到链表头部
// 如果池中有元素,当调用obtain()时,从池中获取表头元素即sPool,
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}
3、消息循环
Looper循环取出MessageQueue中的消息,并将取出的消息发送给Handler进行处理,如果消息队列为空,则线程阻塞。
前面讲到创建Hanlder时通过 Looper类的静态方法 Looper.myLooper(); 获得Looper对象,并获取到MessageQueue对象。
//获取当前线程对应的Looper对象
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
public static void prepare() {
prepare(true);
}
// 创建当前线程的looper对象,并且在之后先调用 loop(),结束时候调用quit()
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对象
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() 方法是在frameworks/base/core/java/android/app/ActivityThread.java中的UI主线程中被调用,初始化主线程looper。
public static void main(String[] args) {
//省略代码 ...
// 初始化主线程looper
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");
}
了解下ThreadLocal
ThreadLocal是Java中的线程内部的数据类,它使得各线程能够保持各自独立的一个对象,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,对于其他线程而言则无法获取到数据.
创建Looper对象后,调用loop() 方法,这个方法会不断的从消息队列中取出、处理消息,
public static void loop() {
final Looper me = myLooper();
// 该方法调用之前先调用 prepare()
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//省略代码 ...
// 核心代码
//获取消息队列
final MessageQueue queue = me.mQueue;
for (;;) {
// 获取消息,might block,可能会阻塞
Message msg = queue.next(); // might block
if (msg == null) {
return;
}
// 处理消息 target 即为Handler
msg.target.dispatchMessage(msg);
// 回收消息,放入消息池中
msg.recycleUnchecked();
}
}
MessageQueue中next() 方法取出消息:
Message next() {
// 省略代码 ...
//获取消息
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
// native 事件处理
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
// java 层 Message对象
Message msg = mMessages;
if (msg != null && msg.target == null) {
// 过滤非isAsynchronous 消息
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;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
// 取出返回消息
return msg;
}
} else {
// 队尾,没有更多消息
nextPollTimeoutMillis = -1;
}
}
}
4、处理消息
Handler接收Looper发送来的消息,并作出相应的处理,主线程操作.
public void dispatchMessage(Message msg){
// msg.callback 其实为Runnable对象,通过Handler的post方法传递过来的
if(msg.callback!=null){
handleCallback(msg);
}else{
// mCallback 不为空,则直接调用handleMessge()
if(mCallback!=null){
if(mCallback.handleMessge(msg)){
return;
}
}
// 如果callback 和 mCallback 都为空,则执行Handler的handleMessage(msg)
handleMessage(msg);
}
}
5、简单总结
1、Handler的工作主要包含消息的发送和接收过程。Handler发送消息向MessageQueue中插入一条消息。
2、MessageQueue的next()方法会取出消息给Looper,Looper接收到消息后开始处理。
3、Looper最终将消息交由Handler处理,调用Handler的dispatchMessage(msg)方法处理。