在Android应用程序进程启动过程的源代码分析一文中,我们分析了Android应用程序进程的启动过程。

为巴州等地区用户提供了全套网页设计制作服务,及巴州网站建设行业解决方案。主营业务为成都网站建设、网站设计、巴州网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
Android应用程序进程在启动的时候, 会在进程中加载ActivityThread类,并且执行这个类的main函数。
应用程序的消息循环过程就是在这个main函数里面实现的。
我们来看看这个函数的实现,它定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
- [java] view plaincopypublic final class ActivityThread {
 - ......
 - public static final void main(String[] args) {
 - ......
 - looper.prepareMainLooper();
 - ......
 - ActivityThread thread = new ActivityThread();
 - thread.attach(false);
 - ......
 - Looper.loop();
 - ......
 - thread.detach();
 - ......
 - }
 - }
 
这个函数做了两件事情,一是在主线程中创建了一个ActivityThread实例,二是通过Looper类使主线程进入消息循环中,这里我们只关注后者。
首先看Looper.prepareMainLooper函数的实现,这是一个静态成员函数,定义在frameworks/base/core/java/android/os/Looper.java文件中:
- [java] view plaincopypublic class Looper {
 - ......
 - private static final ThreadLocal sThreadLocal = new ThreadLocal();
 - final MessageQueue mQueue;
 - ......
 - /** Initialize the current thread as a looper.
 - * This gives you a chance to create handlers that then reference
 - * this looper, before actually starting the loop. Be sure to call
 - * {@link #loop()} after calling this method, and end it by calling
 - * {@link #quit()}.
 - */
 - public static final void prepare() {
 - if (sThreadLocal.get() != null) {
 - throw new RuntimeException("Only one Looper may be created per
 - thread");
 - }
 - sThreadLocal.set(new Looper());
 - }
 - /** Initialize the current thread as a looper, marking it as an
 - application's main
 - * looper. The main looper for your application is created by the Android
 - environment,
 - * so you should never need to call this function yourself.
 - * {@link #prepare()}
 - */
 - public static final void prepareMainLooper() {
 - prepare();
 - setMainLooper(myLooper());
 - if (Process.supportsProcesses()) {
 - myLooper().mQueue.mQuitAllowed = false;
 - }
 - }
 - private synchronized static void setMainLooper(Looper looper) {
 - mMainLooper = looper;
 - }
 - /**
 - * Return the Looper object associated with the current thread. Returns
 - * null if the calling thread is not associated with a Looper.
 - */
 - public static final Looper myLooper() {
 - return (Looper)sThreadLocal.get();
 - }
 - private Looper() {
 - mQueue = new MessageQueue();
 - mRun = true;
 - mThread = Thread.currentThread();
 - }
 - ......
 - }
 
                网站栏目:Android应用程序消息处理机制(Looper、Handler)分析(2)
                
                标题网址:http://www.csdahua.cn/qtweb/news18/543118.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网