Android的Handler机制,我相信是每一位小伙伴面试都经历过的一道题目,Handler机制可以说是Android的很基础但是很重要的内容,因为深入理解了它,很多内容理解起来就变的轻而易举了,比如
AsyncTask
,HandlerThread
,IntentService
内部都用到了Handler机制,今天我们就从源码角度来分析它。
"Only the original thread that created a view hierarchy can touch its views."
异常,这个异常在类ViewRootimpl
中有一个方法checkThread
,如下:void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
解决线程间的切换-这就是Handler机制存在的意义
。activity.runOnUiThread(Runnable action)
来在子线程中更新UI, 我们看到如果当前线程不是主线程,使用的是Handler机制,如果是主线程就直接执行run
方法。final Handler mHandler = new Handler();
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
view.post(Runnable action)或者view.postDelayed(Runnable action, long delayMillis)
来在子线程中更新UI,源码如下,我们可以看到如果attachInfo != null
, 使用的其实还是Handler
机制。有的小伙伴就要问了,那这个AttachInfo
是什么意思呢?在哪里赋值的?如果attachInfo
为空呢,怎么办?还有下面的getRunQueue().post(action);
的逻辑是什么?这些问题限于篇幅,可以看[Android源码解析] View.post到底干了啥这篇文章,里面有详细的讲解,这里简单说一下最后一个问题,其实这里只是将需要执行的任务缓存起来,最终还是通过Handler
机制来处理的。final Handler mHandler
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
Handler
了,在子线程中通过handler.sendMessage(message)
进行使用,这也是我们今天要重点分析的Handler机制源码部分。但是要注意内存泄露,关于Handler的内存泄露部分在文章Android性能优化(二)——内存泄漏中有详细介绍。AsyncTask
,HandlerThread
,IntentService
等,它们内部都封装了Handler
,想要详细了解的可以看Android 多线程:AsyncTask的原理及其源码分析进行了解。Message
,MessageQueue
,Looper
,Handler
, 其实还有一个元素也是很重要的,在Looper
中,它是ThreadLocal
。Message
就是我们要放在队列中被处理的对象。MessageQueue
是一个消息队列,里面存储的自然是消息,但是它不是一个队列,而是一个链表的形式,它仅仅有存储消息的功能,并不能处理消息。Looper
是真正处理消息的地方,它会进入一个无限循环从消息队列中查询是否有新的消息,如果有的话就处理,没有的话就一直等待。Handler
是发送消息的类,会将消息发送到消息队列中,然后Looper
去循环查询消息,进行处理。ThreadLocal
是一个神奇的类,它在Looper.prepare()
方法中使用到了,神奇之处在于它会提供线程隔离,使各个线程之间的数据互相不会影响,尽管使用的是同一个mThreadLocal
对象。在Handler的构造方法通过Looper.myLooper()
,就能获取每一个线程的Looper
, 子线程想要获取looper是得执行Looper.prepare()
的,不然会报异常的,但是在主线程中的ActivityThread
中的main
方法已经执行了Looper.prepare()
方法,所以我们可以直接在主线程使用Handler。enqueueMessage(msg, when)
方法,一个是从队列中取消息的next()
方法。其实MessageQueue并不是真正的队列,它的内部而是维护了一个单链表的结构,因为链表插入删除比较快。enqueueMessage(msg, when)
方法,主要就是根据when
的大小,将消息插入队列中。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) {
// 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;
}
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);
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.
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.
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);
}
}
}
// 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;
}
}
next
中使用的是无限循环,如果队列中没有消息,就会一直阻塞在这里,如果有消息,就会返回这条消息给Looper
进行处理,并且删除队列中的这一条消息。Looper
, 而且不同的线程的Looper不是同一个,这个时候使用ThreadLocal
就可以轻而易举的实现存取Looper
的功能。public class ThreadLocalTest {
private static ThreadLocal mThreadLocal = new ThreadLocal<>();
public static void main(String[] args) {
mThreadLocal.set("main");
System.out.println("main value:" + mThreadLocal.get());
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mThreadLocal.set("thread1");
System.out.println("thread1 value:" + mThreadLocal.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mThreadLocal.set("thread2");
System.out.println("thread2 value:" + mThreadLocal.get());
}
}).start();
}
}
main value:main
thread1 value:thread1
thread2 value:thread2
mThreadLocal
对象,但是在主线程和各个子线程中获取的值却是不一样的。这是因为当调用get
方法的时候,首先会获取当前的线程中的ThreadLocalMap
,它是一个以ThreadLocal
自身为key, 要存储的值为value的一个可以理解为Map的东西, 实际上是一个数组,因为我们存储的时候是用不同的线程中的ThreadLocalMap
进行存储的, 所以获取的值在不同的线程中自然也不一样,所以就互相不影响。我们下面从源码的get
和set
来分析一下ThreadLocal
。public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
set
方法是首先获取当前的线程,然后调用一个getMap(t)
并且把获取的线程传入进去,这时候返回的是t.threadLocals
,t.threadLocals
在Thread
中的定义是ThreadLocal.ThreadLocalMap threadLocals = null
, 其实就是一个ThreadLocal.ThreadLocalMap
,然后就以ThreadLocal
自身为key
, 把值存入到线程所在的ThreadLocalMap
。下面我们看获取的逻辑:public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap
, 然后以ThreadLocalMap
为key
, 获取之前存入的值,这样每个线程获取的值只和当前线程有关,这就是ThreadLocal
的神奇之处。ThreadLocal
主要使用在Looper中, 下面我看关于Looper源码的分析。prepare()和loop()
,首先看Looper.prepare()
方法。public static void prepare() {
prepare(true);
}
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));
}
从prepare
中看到使用到了我们上面提到的ThreadLocal对象。首先判断了sThreadLocal.get()是否为空,如果为空的话就抛出异常,这里说明prepare()方法只能被调用一次。如果为空的话就存储当前线程的Looper到ThreadLocal
中。然后进入Looper
的构造方法中。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在构造方法中我们看到会创建一个MessageQueue
。这个MessageQueue是Looper的成员变量,在Handler的构方法中,我们获取到了Looper之后,通过Looper就可以获取到Looper所持有的MessageQueue。
下面看Looper中另一个重要的方法loop()
方法,源码如下。
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;
// 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;
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 {
//-----1-----
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();
}
}
这个looper()
方法是Handler机制中处理消息的方法,从for (;;)
看出,它会进入一个无限的循环,从消息队列MessageQueue
中调用queue.next()
获取消息, 如果队列中没有消息,线程就会阻塞; 当通过handler.sendMessage(Message msg)
有新消息的时候, 调用的是queue.enqueue
方法,会将Message添加到队列中,并且判断是否需要唤醒线程。
在注释1
处我们看到调用了msg.target.dispatchMessage(msg)
来处理消息,查看Message源码知道这里的target
其实就是Handler。下面我们来分析Handler
的源码部分。
Looper
的话,最终源码如下: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;
}
Looper
的话,最终源码如下:public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
Looper.myLooper()
来获取当前线程的looper
, 如果这个Handler是在主线程创建的,那么我们获取到的looper
, 其实就是在ActivityThread.main
中通过Looper.prepareMainLooper()
创建的,所以我们不需要手动调用Looper.prepare()
创建。如果这个Handler是在子线程创建的,那么我们获取到的looper
就为null, 就会抛出一个异常"Can't create handler inside thread that has not called Looper.prepare()")
。所以我们在子线程中使用Handler的时候一定要记得调用Looper.prepare()
去创建Looper(可以参考HandlerThread
源码学习)。Looper
持有的MessageQueue
赋值为Handler中的成员变量。handler.sendEmptyMessage(msg)
, 但是最终都进入到的是sendMessageAtTime
方法,下面我们通过源码看下。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) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
queue.enqueueMessage
将消息加入MessageQueue
中。加入到消息队列中,而Looper.loop()
方法回不停的从队列中取出消息,调用msg.target.dispatchMessage(msg)
来处理消息,前面我们知道实际调用的是handler.dispatchMessage(msg)
,我们通过源码来看下这个方法: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();
}
msg.callback != null
, 这里这个callback
其实是通过handler.post(runnable)
发送的一个runnable, 如果不为null的话就执行handleCallback(msg)
,这个方法看上面的源码,其实就是执行runnbale中的代码而已。mCallback != null
就会执行mCallback.handleMessage(msg)
中的逻辑,这个mCallback
其实是其中一种构建Handler的构造方法中的参数,Handler handler = new Handler(callback)
;handleMessage
来处理,这个方法是需要我们重写的方法,里面根据Message处理我们的逻辑。Looper.prepare
方法将新建的looper
存储在ThreadLocal
中,并且在Looper
的构造方法中创建一个MessageQueue
。然后创建Handler
实例,在Handler
的构造方法中获取当前线程的looper
以及通过looper获取到MessageQueue
。再然后就调用Looper.loop()
方法开始无限循环MessageQueue
,等待有消息就处理。接着通过handler.sendMessage
发送消息,将消息加入MessageQueue
中,而looper这时候收到新来的消息时候,就会调用handler.dispatchMessage(msg)
进行消息处理。Handler
是在主线程创建的,我们知道主线程的Looper
在ActivityThread.main
中就创建了,接着调用Looper.loop()
方法,这个方法是在主线程无限循环处理消息的,如果我们从子线程发送一个Message
, 这时候主线程在Looper.loop()
方法中通过queue.next()
获取的Message
会通过msg.target.dispatchMessage(msg)
,也就是handler.dispatchMessage(msg)
来处理消息,而这个dispatchMessage
就是在主线程中执行的,最终实现了线程的切换。