还是ActivityThread这段代码。来自Android中为什么主线程不会因为Looper.loop()里的死循环阻塞?
我们知道APP的入口是在ActivityThread,一个java类,有着main方法,而且main方法中的代码也不是很多.
public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingPRofilerIntegration.start(); // 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()); AndroidKeyStoreProvider.install(); // 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(); ActivityThread thread = new ActivityThread(); thread.attach(false); 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"); }在上篇文章MessageQueue与Looper的由来我们得知这段代码中的Looper.prepareMainLooper()
在主线程中创建了一个Looper对象,然后在这段代码的末尾处,调用了Looper.loop()
方法,我们来看看Looper.loop()
源码:
从这个loop()
方法中逻辑就比较明了了,里面有一个死循环,从消息队列中不断的取出消息,然后调用这个方法msg.target.dispatchMessage(msg)
,msg.tagre
为当初你创建的Handler对象,因为在Handler把消息放入消息队列的时候执行了以下代码:
可以看到这里把创建的Handler赋值给了msg.target
。然后msg.target.dispatchMessage(msg)
就相当于handler.dispatchMessage(msg)
,所以我们来看看Handler的dispatchMessage()方法:
如果看过第一篇Handler消息发送我们就可以了解到Handler是如何发送消息的,所以看到这段代码就应该知道这些消息或者是回调是如何发送的了。
根据自己的理解,绘制了以下流程图,如有错误,请及时提醒我改正:
这个系列是本人写的第一篇比较完成的博客,肯定会有非常多的不足,希望大家能够多留言批评,希望能明确指出文章中可能有的错误,我会及时更正,谢谢。
系列目录:
一定搞懂Handler消息处理机制系列之「01.Handler消息发送」
一定搞懂Handler消息处理机制系列之「02.Message入列」
一定搞懂Handler消息处理机制系列之「03.MessageQueue与Looper的由来」
一定搞懂Handler消息处理机制系列之「04.Message是如何触发的」
新闻热点
疑难解答