一、概述
上篇内容给大家分享了HandlerThread和IntentService,那篇文章的理解需要基于Handler机制,本篇内容就写点Handler相关的内容,如果你已经理解Handler的工作机制,本篇内容可以绕过。
大家在Android应用开发过程中,对Handler使用是比较多的,但大多情况下是用于线程之间的切换,但线程之间的通信是如何做到切换呢?本文将给大家分享下Handler的工作原理。
二、源码分析
本文就不给大家讲解Handler如何使用了,Talk is cheap,Show me the code.
如果给大家讲Handler如何使用,那就显得太没有逼格了,废话不说,直接上Handler的构造函数源码:
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();//获得Looper
if (mLooper == null) {//如果没有Looper 将会报运行异常
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
//Looper 中的myLooper()方法
public static @Nullable Looper myLooper() {
//从ThreadLocal中获取该Looper ThreadLocal的原理后边给大家
//ThreadLocal 你可以理解为保存一个在线程范围内可见的变量 我们把Looper的实例保存了进去
return sThreadLocal.get();分析
}
//sendMessage(Message msg)方法最终会调用该方法
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;//target 赋值
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);//最终执行的是MessageQueue的enqueueMessage方法
}
从Handler的源码中可以看出:
- 获得当前线程Looper;
- 如果当前线程没有Looper 报运行时异常;
- sendMessage方法最终是往MessageQueue队列中添加Message节点;
- 加入队列前,为Message的target赋值。
说明Handler的工作离不开Looper。那Looper是什么呢?
我们先瞅瞅HandlerThread是如何使用Looper的:
//HandlerThread 中run()方法如下
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();//先调用prepare()静态方法 该方法会启动一个可以终止的Looper
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();;//再调用loop()静态方法
mTid = -1;
}
接下来我们瞅下Looper的源码(省略部分方法和注释):
public final class Looper {
final MessageQueue mQueue;//从名字看 是一个消息队列
final Thread mThread;
private Printer mLogging;
private long mTraceTag;
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {//参数表示该Looper是否可以终止
if (sThreadLocal.get() != null) {//一个线程只能有一个Looper
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));//为线程范围内保存Looper实例
}
//Android主线程保存了一个不可以停止的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();
}
}
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
//该方法是启动Looper的循环
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;//获取Looper的消息队列
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {//核心部分 启动一个死循环
Message msg = queue.next(); // 可能会阻塞
if (msg == null) {//如果msg 为null 该死循环将被终止
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//msg的target变量调用dispatchMessage()方法,这时你估计能猜到target是一个Handler对象,后边验证我们的猜想
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
public static @NonNull MessageQueue myQueue() {
return myLooper().mQueue;
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
//停止Looper主要通过改变MessageQueue中的mQuitting 状态,如果该状态为true,则next()方法返回null来停止Looper的死循环.
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
}
从Looper我们可以看出:
- 内部有一个静态ThreadLocal sThreadLocal变量,用于存储Looper实例
- 保存了一个MessageQueue mQueue属性变量,从名字看是一个消息队列;
- 调用prepareMainLooper()或者prepare()方法, 主要在sThreadLocal存储Looper实例对象;
- 调用loop()方法,启动一个死循环,从mQueue队列中取消息,这步可能阻塞死循环。
- 停止Looper主要通过改变MessageQueue中的mQuitting 状态,如果该值为true,则next()方法返回null来停止Looper的死循环.
接下来我们看下MessageQueue 的实现,主要看两个方法 next()和enqueueMessage(),先看next()方法:
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
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);//调用native方法
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) {//msg.target ==null ?入队列时候为null会报空异常 要语句块始终不会运行?
// Stalled by a barrier. Find the next asynchronous message in the queue.
//从队列中找异步的消息,Message的flag状态有关
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;
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) {//跟Looper的quite()方法有关 前边讲过 msg == null的话 ,Looper会终止循环
dispose();
return null;
}
//主要用于处理 IdleHandler
// 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) {//没有IdleHandler 就直接下次循环
// 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++) {//遍历IdleHandler
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();//调用IdleHandler 的queueIdle()方法 返回值决定了是否保留该IdleHandler
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);//移除该queueIdle
}
}
}
// 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;
}
}
在MessageQueue的next()方法中主要做了:
- 遍历Message队列,找到要执行的Message返回;
- 未找到Message,则计算出要阻塞时间,然后在native方法中阻塞;
- 每次遍历Message都会遍历IdleHandler;
- 如果mIdleHandlers列表不为null,则nextPollTimeoutMillis会为0,表明下次不会阻塞;
下边看下Message的enqueueMessage 方法:
boolean enqueueMessage(Message msg, long when) {
//msg.target不能为null 但next()方法体中有一个判断当当改值为null的情况不是很理解,欢迎大家讨论
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) {//队列为null情况
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {//不为null情况
// 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) {//根据Message的wen绝对在队列中的位置
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的enqueueMessage中主要做了:
- 判断target是否为null,为空则跑出异常,不明白next()方法中if (msg != null && msg.target == null)该语句块是否会执行,欢迎评论来讨论;
- 根据when来决定消息在队列中的位置,取消息和放消息都在同步块中执行;
Message 的quit()方法:
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) {//p.when > now 清除链表
removeAllMessagesLocked();
} else {//p.when <= now
Message n;
for (;;) {//改循环找出p.when > now的节点
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);//清除没到执行点的节点
}
}
}
Message的quit()主要做了:
- 不安全结束的做法是直接清除队列,然后唤起阻塞;
- 安全结束的方法是找出所有的执行节点,把未到执行时间的节点清理掉,然后唤醒阻塞;
三、结语
我们可以把Handler消息机制理解为生产消费模型:
- Handler是生产者,主要往MessageQueue中存放消息;
- Looper为消费者,主要从MessageQueue中消费消息;
以上就是为大家分享的Handler消息机制,感谢你的耐心阅读,如有错误,欢迎指正。如果本文对你有帮助,记得点赞。欢迎关注我的微信公众号。