今天我阅读了一些关于Handler和Looper如何协作的博客和源代码。
根据我的学习,我们可以通过使用ThreadLocal技巧,在每个线程上只有一个Looper。通常情况下,Handler在主线程中初始化,否则您必须手动启动或者说,准备单独的线程中的Looper,然后循环它。
我真正困惑的是主线程中的
根据这个https://dev59.com/9W435IYBdhLWcg3w0Tnc#5193981,Handler 和它的 Looper 运行在同一线程中。
如果主线程上有一个无限循环,那么它不会阻塞整个 UI 系统吗?
我知道我一定很傻才会错过什么。但对于某人揭示其中的秘密,这将是可爱的。
根据我的学习,我们可以通过使用ThreadLocal技巧,在每个线程上只有一个Looper。通常情况下,Handler在主线程中初始化,否则您必须手动启动或者说,准备单独的线程中的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://dev59.com/9W435IYBdhLWcg3w0Tnc#5193981,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();
}
}
for(;;){ }
循环,那么如何发送消息以绘制用户界面呢? - Ryan HooAndroidThread.H
的问题,这是关于android IPC Binder设计的一个话题,ActivityManagerService
、ActivityThread
和ApplicationThread
之间存在关系(类名不确定,抱歉我的记忆不好)。您可以在一些博客或直接查看源代码中了解更多详细信息。 - Jian Guo