Handler作为android开发中最常见的一个类,想必大家用过很多次,它的用法是android开发必须掌握的基本技能之一。此次我们就来阅读Handler相关源码,探索其线程切换的内部实现!
1、Looper
我们都知道,在非主线程使用Handler必须先调用Looper类的两个方法(主线程默认已完成这两步):Looper.prepare()和Looper.loop()。那么Looper和Handler究竟有什么样的关系?我们先来看Looper的部分代码,看看是否能得到有用的信息。
public final class Looper {
// sThreadLocal.get() will return null unless you've called prepare().
//线程与Looper绑定,一个线程对应一个Looper对象
static final ThreadLocal sThreadLocal = new ThreadLocal();
private static Looper sMainLooper; // guarded by Looper.class
//消息队列
final MessageQueue mQueue;
//Looper对象对应的线程
final Thread mThread;
/* 如果设置了该值,则如果消息分派花费的时间超过时间,则looper将显示一个警告日志。 */
/* If set, the looper will show a warning log if a message dispatch takes longer than time. */
private long mSlowDispatchThresholdMs;
/** Initialize the current thread as a looper.初始化线程对应的Looper
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
//判断线程是否已有Looper,一个线程只能创建一个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);
//持有Looper对应的线程引用
mThread = Thread.currentThread();
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
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.");
}
final MessageQueue queue = me.mQueue;
// 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(); // might block
if (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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
//trace日志能否打印的标记
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
//发送起始时间
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
//消息分发到对应的Handler
msg.target.dispatchMessage(msg);
//发送结束时间
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//设置了超时时间,而且超时了,打印日志
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
}
从Looper.prepare()和Looper.loop()两个方法的源码来看,可以得到以下结论:
1、线程和Looper是一一对应的,这个关系通过ThreadLocal
2、Looper内部维护了一个消息队列,所有发送给线程的Message对象都存储在这个消息队列中。
3、消息发送的最终代码是“msg.target.dispatchMessage(msg)”;所以如果有人问你一个线程创建了多个Handler,那消息是如何找到它对应的Handler?你只需要跟他说消息Message自己带有目标Handler对象的索引....
4、loop()方法里除了事件分发其实没做什么,大部分代码都是为了打印跟踪日志,当然包括了超时日志。
5、Looper.loop()方法里面通过死循环来实现事件的轮询分发,只有在消息队列退出(即queue.next()返回为空)时死循环才会停止,queue.next()何时返回为空,后续看MessageQueue源码。
2、Handler
说完Looper我们再来看Handler,跟上面一样我们依旧从方法调用来看Handler的消息发送流程:
Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
Message msg = Message.obtain();
mHandler.sendMessage(msg);
首先我们来看Handler的无参构造函数里面做了什么:
public class Handler {
/*
* Set this flag to true to detect anonymous, local or member classes
* that extend this Handler class and that are not static. These kind
* of classes can potentially create leaks.
*将此标志设置为true以检测不是静态的匿名、本地或成员的继承Handler的类。
*这种类可能会造成泄漏。
*/
private static final boolean FIND_POTENTIAL_LEAKS = false;
/**
* Default constructor associates this handler with the {@link Looper} for the
* current thread.
*默认构造函数将这个handler与当前线程的{@link Looper}关联起来。
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*如果此线程没有looper,则此处理程序将无法接收消息,并抛出异常。
*/
public Handler() {
this(null, false);
}
/**
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
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());
}
}
//获取线程对应的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//引用Looper的消息队列
mQueue = mLooper.mQueue;
//回调接口赋值
mCallback = callback;
mAsynchronous = async;
}
}
Handler初始化主要是跟线程对应Looper建立联系,并获得消息队列的引用方便之后发送流程中消息的缓存。
接下来我们来看Handler.sendMessage(msg)方法,探究消息发送的内部实现:
public class Handler {
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
//延迟时间不能小于0
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
//设置消息是否异步,这意味着它不受Looper同步屏障的约束。
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
/**
* Handle system messages here.
*/
public void dispatchMessage(Message msg) {
//优先消息自带callback
if (msg.callback != null) {
handleCallback(msg);
} else {
//Handler的成员变量callback次级
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//Handler的handleMessage()方法最后
handleMessage(msg);
}
}
}
是的兜兜转转调了几个接口后,你会发现发送的最终逻辑是往MessageQueue里面塞Message,Handler的另外一个重要任务就是把Handler对象赋值给消息Message的成员变量target!!!!
其实看完上面两个类的源码,我们大体上已经可以理清Handler的整个机制了:
1、线程通过ThreadLocal对应一个唯一的Looper;
2、Looper拥有一个MessageQueue消息队列成员变量,并且开启了死循环轮询MessageQueue实现事件分发;
3、Handler则是将持有本身引用的Message放进MessageQueue,并等待Looper分发Message。
4、Handler最终分发Message的方法dispatchMessage(Message msg)里面,回调对象的选择有主次之分:优先消息自带callback,Handler的成员变量callback次级,Handler的handleMessage()方法最后
最后我们再来看看MessageQueue里面的代码,看看queue.next()是如何实现只在退出时返空的,看看queue.enqueueMessage(msg, uptimeMillis)方法具体实现:
public final class 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) {
//队列正在退出,不能再添加Message,抛出异常
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) {
// New head, wake up the event queue if blocked.
//新的队列头部消息,唤醒事件队列如果阻塞。
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// 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) {
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 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.
//如果消息循环已经退出并被释放,则return。
//如果应用程序在退出后试图重新启动looper(不支持该操作),就会发生这种情况。
//mPtr默认为0,MessageQueue 初始化是赋值,quit()或dispose()方法重置为0.
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) {
// 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.
//现在所有挂起的消息都已处理完毕,处理quit消息。
if (mQuitting) {
dispose();
return null;
}
// 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.
//如果第一次空闲,则获得要运行的空闲组的数量。
// 空闲的handlers只在队列为空或队列中的第一个消息(可能是一个障碍)将要处理时运行。
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
//重新赋值pendingIdleHandlerCount
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
//没有要运行的空闲handlers 。循环并等待更多。
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.
//运行空闲handlers。
//我们只在第一次迭代中到达这个代码块。
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);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
//将空闲handler 计数重置为0,为了不再运行它们。
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.
//在调用空闲handler时,可能已经传递了新消息,因此返回并再次查找未等待的消息。
nextPollTimeoutMillis = 0;
}
}
}
看完上面两个方法后,我们再结合之前Looper和Handler的代码,可以得出以下结论:
1、Looper里面开启死循环通过MessageQueue.next()方法从队列里面拿Message,MessageQueue.next()方法只有在MessageQueue退出时才会返回null,进而停止Looper里面的死循环,其它情况下要么返回某个Message要么在next()里面死循环遍历查找消息。
2、MessageQueue.enqueueMessage(msg, uptimeMillis)确实是往队列中插入Message,一般插到当前指针的下一个位置或者队列头部。