今天我阅读了一些关于 Handler 和 Looper 如何协同工作的博客和源代码。
根据我所学到的,我们可以通过使用ThreadLocal
魔法在每个线程上只有一个 Looper。通常Handler是在主线程中启动的,否则你必须手动启动或者说,prepare
Looper在一个单独的线程上然后循环起来。
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();
}
}
真正让我感到困惑的是loop()
主线程。正如我在 Looper 的源代码中读到的那样。处理消息队列然后调度消息以供回调处理是一个无限循环。
根据这个https://stackoverflow.com/a/5193981/2290191, Handler 和它的 Looper 在同一个线程中运行。
如果主线程出现死循环,岂不是阻塞了整个UI系统?
我知道我一定是太傻了才会错过一些东西。但如果有人透露这背后的秘密,那就太好了。
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
}