Android消息机制之Handler
关键类:Looper,MessageQueue,Handler,Message
关键方法:Lopper.prepare(),handler.sendMessage(),Lopper.loop()
简单介绍
- Lopper持有MessageQueue消息队列,且执行消息的取出并发送
- MessageQueue它是一个消息队列,用于将所有收到的消息以队列的形式进行排列,并提供入队和出队的方法。
- Handler主要执行消息的存入及接收
- Message作为存储数据的媒介
从上我们可以大致理解Handler机制的流程为:1.准备、2.存入消息、3取出&发送消息、4.接收消息。而存取消息我们必须拥有一个队列即MessageQueue。
- 准备:Lopper.prepare()实例化Looper,实例化MessageQueue
- 存入:Handler.sendMessage()将消息存入MessageQueue中(PS:这是存入,不是发送)
- 取出&发送:Lopper.loop()通过阻塞模式死循环,不断取出消息,并调用disPatchMessage()进行发送
- 接收:Handler通过handleCallBack或handleMessage进行接收消息
理解图
源码解读:
Step1:Looper类 ->准备
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//判断是Looper是否为空
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();
}
大家此时对sThreadLocal可能有点疑惑,这里简单理解为存储Lopper的变量,具体了解请进传送门
prepare()方法主要实例化Looper对象,在实例化Looper的同时也实例化队列MessageQueue
Step2.1: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的过程中,最主要的方法为 mLooper = Looper.myLooper();
获取Lopper的对象,并将Queue和CallBack等进行赋值
Step2.2:Looper类
public static Looper myLooper() {
return sThreadLocal.get();
}
刚刚Step1疑惑的sThreadLocal又出现了!sThreadLocal.get()
直接获取Looper对象。此时的Handler已经拥有了Looper,MessageQueue,CallBack等重要的类及其接口
Step3.1:Handler类 ->存入消息
我们平时使用sendEmptyMessage(int what)
,sendMessage(Message msg)
进行发送消息。但是这里得纠正一下,虽然方法名叫做发送消息,但它实质上进行的是存入操作。除了上面提的2个方法,Handler中还有以下类似的方法:
-
sendMessageAtTime(Message msg, long uptimeMillis)
- sendEmptyMessageDelayed(int what, long delayMillis)
- sendMessageDelayed(Message msg, long delayMillis)
- sendEmptyMessageAtTime(int what, long uptimeMillis)
-
sendMessageAtFrontOfQueue(Message msg)
三个小方法最终都调用了sendMessageAtTime。sendMessageAtTime和sendMessageAtFrontOfQueue都调用了enqueueMessage,将消息加载至队列
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 boolean sendMessageAtFrontOfQueue(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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
以上两个方法唯一的区别就是enqueueMessage的第三个参数。enqueueMessage中,msg将当前的Handler进行绑定,并调用MessageQueue的enqueueMessage
Step3.2:MessageQueue类 ->存入消息
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) {
//排序至首部
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
//通过for循环来判断当前message应该所出的位置
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;
}
此时的消息通过遍历next的操作,添加至MessageQuue,可看出此消息队列是通过类似C语言的链表来存储这些有序的消息。其中mMessages对象表示当前待处理的消息。从上还可以看出消息插入的队列的方式是按所有消息的时间进行排序。所以Step3.3中sendMessageAtFrontOfQueue()传入给enqueueMessage的uptimeMillis参数为0,所以他可以排至队列的头部
Step4.1:Lopper类 ->取出&发送
public static void loop() {
final Looper me = myLooper();//获取Looper
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(); // 有可能会被阻塞
if (msg == null) {
return;
}
......
try {
//分发消息
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
......
msg.recycleUnchecked();
}
}
首先Loop()中,先获取Looper的对象,接着获取相对应的MessageQueue消息队列。接着进入一个死循环,不断的调用MessageQueue的next()方法,如果取出的msg为空即队列已经空的情况下,退出死循环。而msg不为空的情况下,调用dispatchMessage分发消息。
Step4.2:MessageQueue类 ->取出&发送
Message next() {
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) {
//下一个消息还没准备,设置一个超时值,当消息准备好时进行唤醒
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 {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {//退出重要标志
dispose();
return null;
}
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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}
可以看出来,这个next方法就是消息队列的出队方法(与上面分析的MessageQueue消息队列的enqueueMessage方法对比)。可以看见上面代码就是如果当前MessageQueue中存在待处理的消息mMessages就将这个消息出队,然后让下一条消息成为mMessages,否则就进入一个阻塞状态,一直等到有新的消息入队。
Step4.3:Handler类 ->取出&发送
当我们把消息一个个取出来的时候,此时消息也开始分发msg.target.dispatchMessage
。target是什么呢?请会看Step3.1中的enqueueMessage()里的msg.target=this
,this即为Handler。
/**
* Handle system messages here.
*/
public void dispatchMessage(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();
}
从上面代码可以看出。分发的时候会先判断Message本身是否有callback回调,有的话优先调用handleCallback(msg)
。接着判断Handler本身是否有callback回调,有则掉之,无则使用我们熟悉的handleMessage(msg)
Step5.1:Looper类 ->结束
由于我们MessageQueue消息队列是一个死循环的阻塞等待,所以当我们把所有的Message发送完毕后,会将此循环结束掉!
public void quit() {
mQueue.quit(false);
}
quit方法实质就是调运了MessageQueue消息队列的quit
Step5.2:MessageQueue类 ->结束
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);
}
}
quit方法首先判断此线程是否允许退出,看Throw的错误,我们可以看出:主线程是不允许退出的。此时有小伙伴会疑惑mQuitAllowed从哪里冒出来的?可以参考Step1的MessageQueue的构造方法。所以我们可以推测UI线程的MessageQueue构造方法传入的是false!
Looper类
public static void prepareMainLooper() {
prepare(false);//传入false
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
果然如此!prepare()方法,请参考Step1!
回到quit方法中mQuitting=true
的标志。而此标志在MessageQueue的紫色等待next方法中做判断,请参考Step4.2。所以通过quit方法退出整个当前线程的loop循环。
到此完整的Handler的使用流程结束。
总结 Summary
- 一个线程中只有一个Looper实例,一个MessageQueue实例,可以有多个Handler实例。
- sendMessage()实质是存入消息至队列,真正的发送是Lopper.loop()
- 消息的回调总共有3种方式:1.Message的回调、2.Handler的回调、3.Handler的handMessage()
额外 Extra
1.postDelayed
post(Runnable r); postDelayed(Runnable r, long delayMillis);
等post系列方法。
该方法实质源码其实就是如下:
public final boolean postDelayed(Runnable r, long delayMillis)
{
return sendMessageDelayed(getPostMessage(r), delayMillis);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
原来post方法的实质也是调运sendMessageDelayed()方法!!!getPostMessage即将对应的Runnable赋值给消息的callback回调。在handler的dispatchMessage方法中首先判断Message的callback是否为空,不为空则调之。(优先级高)请参考Step4.3
2. runOnUiThread
此为Activity刷新UI的方法
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
判断是否为UI线程,否则调用mHandler.post
,是则直接执行Runnable的run方法
PS:本文
整理
自以下文章,若有发现问题请致邮 caoyanglee92@gmail.com
工匠若水 Android异步消息处理机制详解及源码分析
网友评论