Android 消息机制

来源:互联网 发布:贪心算法实例 编辑:程序博客网 时间:2024/06/04 20:07

网上已经有很多这方面的博客了,所以很多细节就不重复写了。

写这篇是因为我突然有个疑问:主线程为什么不会关闭?是在执行什么代码?
其他的只是我了解过程中看到资料,顺便整理的。

1. Message、Handle、Looper、MessageQueue:

已经有很多详细的介绍了,就不多写了。推荐链接:
http://blog.csdn.net/lmj623565791/article/details/38377229

2. 消息处理过程:

http://www.jianshu.com/p/ad225c1091e4

3. 在Android系统中的应用:

我们都知道一个线程在所有代码运行完之后就会销毁,但是在Android中,主线程确是一直都在运行的,直到App关闭。那主线程到底是一直在运行什么代码呢?
我们知道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());        // 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");    }

可以看到在最后运行了Looper.loop()方法,而这个方法是堵塞的,也就是说其实主线程是一直堵塞在looper的loop方法中的。

既然主线程平时是堵塞的,为什么Activity还会执行各个生命周期回调?
看过Activity启动过程的都应该知道,Activity的各个生命周期都是通过Handler处理的。
具体可以查看:
http://blog.csdn.net/singwhatiwanna/article/details/18154335

原创粉丝点击