探究Handler的运行机制
Handler 作为 Android 开发中重要的消息通讯的工具,在我们日常开发中经常使用到,虽然经藏使用,也是一知半解,所以今天就去看一下 Handler 的源码到底怎么实现的呢?
1 Handler 是什么呢?
众 android 开发者周知, Handler 是我们用来进行线程间通讯的工具。像我们网络请求返回的数据,就会经常使用Handler把数据回传给主线程。然后主线程展示相关数据。
2 为什么要用 Handler 呢?
android 要求耗时的任务要在子线程中进行,不然会造成UI界面的卡顿,而我们的 UI 界面是在主线程。要把子线程的数据显示到主线程则就要用到 handler 了,不然,你在子线程直接刷新UI界面,程序会报错。
3 看下我们平时如何用 Handler 的呢?
public class TestActivity extends AppCompatActivity {
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case 0x1111:
Toast.makeText(this,"收到子线程发来的消息了",Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(){
@Override
public void run() {
Message message = Message.obtain();
message.obj = "这是一个handler消息";
message.what = 0x1111;
handler.sendMessage(message);
}
};
}
}
上面代码是我们 Handler 的常用方式,接下来去看下它内部具体是怎么实现的呢?进入源码中去查看;
(1) 首先咱们看一下创建Handler都去做了哪些工作。
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
调用构造方法:
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 " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看到 handler 构造的过程中,如果你定义 handler 用了 static 修饰符的话,还会提示你会出现内存溢出的风险(这里和静态持有 Activity 有关)。接下来会去获取到一个 Looper 对象。同时把
Looper 类里面的消息队列 mLooper.mQueue 赋值给了 Handler 类里面的队列常量 mQueue。下面我们继续看如何获取 Looper 对象的。
mLooper = Looper.myLooper();
进入到Looper类中。
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
在 Looper 类里面维护了一个 sThreadLocal 的常量,我们获取到的 looper 是从这个常量中取的,既然是取的,那就一定会有地方去存储这个变量,并且这个设置的方法一定在我们构造函数之前。我们沿着关键字搜索发现在 prepare 方法的确有设置 looper 的方法:
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 方法呢,于是按着方法调用一路往上寻找:
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
这里看门看到 Looper 类中的调用 prepareMainLooper() 方法,这里如果我们是在主线程里面创建的 Handler 对象就会调用到 prepareMainLooper() 方法,而事例中我们就是在主线程中调用,继续去查找调用 prepareMainLooper 方法的地方:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
因为和主线程有关,我们就可以看看与主线程相关的线程类,在 ActivityThread 类主运行程序中找到了 prepareMainLooper() 方法,同时证明了在主线程中的确在我们构造 Handler 之前就已经初始化了 Looper 这个类,并设置到了ThreadLocal对象中。同时代码最后有个 Looper.loop() 方法先记下来,后续这里也会提到。
Looper 类的设置和获取在这里都已经完成。这了顺便看一下为什么 Looper 创建了之后要放在一个 ThreadLocal 对象的数据结构里面?去看看 ThreadLocal 这个类干嘛的:
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();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
因为在 ThreadLocal 中主要用了 get 和 set 方法,我们主要看这两个方法。在这里,看到我们有个 ThreadLocalMap 通过线程 Thread 获取的。于是我们可以猜想到 ThreadLocal 是为了保证每个线程对应一个Looper,这样保证每个线程独享一份数据。
到这里我们 Handler 整个初始化的过程涉及到的类进行了挖掘。目前主要涉及到Handler、Looper、ThreadLocal、MessageQueue 四个类。
(2) 接下来我们看在子线程里面发送消息的时候,此时这些类又做了些什么呢?有没有其他的类再次参与进来呢?
接下来继续 Handler 类中发送消息的相关代码细节:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
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) {
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);
}
sendMessage 方法最终会调用到 MessageQueue 里面的enqueueMessage 方法,继续到 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) {
// 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;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
定位到上述这段主要代码,记录当前msg相关信息,并且如果当前MessageQueue 的 mMessages 为空的时候则会把这条消息当作第一条消息,设置相关的标记位。如果不为空,遍历循环出需要wake 唤醒发送的消息,则加到最后一条去。这里同时可以看到 MessageQueue 数据结构采用的是链表结构。最后调用到nativeWake 明显到了 native 层的调用,我们从处理消息的代码再进行回推。
我们继续来到Handler类中,查找处理消息的 handleMessage 方法:
public void handleMessage(Message msg) {
}
/**
* 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);
}
}
dispatchMessage 后在 Handler 类中没发现其他地方调用,在上面提到的其他三个相关联的类再去找找。
最终我们来到 Looper 类中的 loop 方法,里面可以看到 msg.target.dispatchMessage(msg) 方法,loop 这个方法我们在ActivityThread 中提到过会被调用,也就是说程序主线程启动的时候 dispatchMessage 方法就在一直执行了 ,那就看看 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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
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 traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
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();
}
}
定位到for语句死循环那段代码:
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
....
}
不断遍历去取消息队列里面的数据,只有当拿不到 msg 数据的时候会停止。 继续看 MessageQueue 类中 queue.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() 方法里面也有个死循环,其主要的作用就是要去取到下一个待处理的 msg,取到 msg 之后最终会传到 handler 的 handlerMessage 方法进行处理。这样我们就从handlerMessage 方法中取到了下一条待处理的消息数据;
至此整个方法链就连上了。最后我们总结一下:
1 首先,创建 Handler 的主线程会通过 ActivityThread 去创建一个 Looper ,并通过 prepare 方法,把当前线程和 Looper 绑定存到一个 ThreadLocal 类中。同时会开启 Looper 的 loop() 方法进行死循环查找信息。
2 当 Handler 初始化的时候,handler 会拿到 looper 类,同时将 looper 的 MessageQueue 赋值给 handler 中的 MessageQueue 队列。
3 Handler发送消息,此时会将消息添加到 handler 中的 MessageQueue 的最后面,同时 Looper 中的 looper 循环会取 MessgeQueue 中的消息,通过 Handler 的 dispatchMessage 分发到handlerMessage 最终处理调 msg 事件信息。
最后有个面试问到的问题,如果是在子线程里面可以创建 Handler 发送和接收消息嘛?
/**
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.
*
* <p>Most interaction with a message loop is through the
* {@link Handler} class.
*
* <p>This is a typical example of the implementation of a Looper thread,
* using the separation of {@link #prepare} and {@link #loop} to create an
* initial Handler to communicate with the Looper.
*
* <pre>
* class LooperThread extends Thread {
* public Handler mHandler;
*
* public void run() {
* Looper.prepare();
*
* mHandler = new Handler() {
* public void handleMessage(Message msg) {
* // process incoming messages here
* }
* };
*
* Looper.loop();
* }
* }</pre>
*/
可以看到 Looper 类上面的注释,当然是可以的了。只不过我们要自己创建 Looper 了并且去调用 prepare 和 loop 方法循环查找消息。不然直接在子线程处理消息,程序会报错。