Handler机制是由Looper和MessageQueue以及Message来构建消息机制的
为了便于理解我们拿子线程的使用说起:
使用方法Looper.prepare() -> new handler() -> Looper.loop()
注意主线程里ActivityThread已经为我们做了这些工作
就拿使用的方法顺序流程开始分析:
Looper.prepare()
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
在Looper.prepare()中,会调用ThreadLocal.set()将该Looper实例set今当前线程Thread的ThreadLocal.ThreadLocalMap里;
new Handler()
public Handler(Callback callback, boolean async) {
//从这里可以看到如果不调用Looper.prepare()会报错的
mLooper = Looper.myLooper();
if (mLooper == null) {
thro

本文深入剖析了Android Handler消息机制,从Looper.prepare()、new Handler()到Looper.loop()的流程,解释了为何Looper.loop()不会阻塞主线程以及在nativePollOnce阻塞状态下仍能发送消息到MessageQueue的原因。通过Handler.sendMessage()、MessageQueue.enqueueMessage()和handleMessage(msg)等关键步骤,揭示了Handler如何协调线程间的消息传递。

2453

被折叠的 条评论
为什么被折叠?



