Android消息机制

Android消息机制

消息机制模型

  • Handler :作为一个具体的执行者,主要作用是发送消息(sendMessage(Message),postAtTime(Runnable ,long))和处理消息
  • Message:定义一些要执行的操作,可能还携带一些数据(arg1,arg2,obj)。
  • MessageQueue:消息队列,主要作用是放入消息(messageQueue.enqueMessage()),取出消息(messageQueue.Next())。每一个MessageQueue是和一个Looper关联的。
  • Looper:不断的轮询,将消息取出来交给Handler去执行
  • ThreadLocal:线程局部类,维护每个线程的Looper。

Android的消息机制具体是指什么?

主要是Handler的机制,包括相关的MessageQueue和Looper一些类的具体运行机制。

主线程不能进行耗时操作,子线程不能更新UI (为什么?)

主线程进行耗时操作就会阻塞主线程,容易发生ANR。而由于Android的view不是线程安全的,如果多线程访问View可能会出现意想不到的问题。

更深入的分析:Android 子线程真的不能更新UI么?

一、Message

消息一般来说都包含相应的操作描述,可能还携带一些数据。Message类实现了Parcelable接口,所以它可以用于进程间通信,确实在Android中也有应用,比如Messenger,就会利用message机制来进程通信。一个Message一般包含以下这些内容。

数据类型成员变量解释
intwhat消息类别
longwhen消息触发时间
intarg1参数1
intarg2参数2
Objectobj消息内容
Handlertarget消息响应方
Runnablecallback回调方法

Message的创建有两种方法:

  • New Message();
  • Message.obtain()

一般来说,选择obtain()方法,因为这个方法是从消息池中取出消息,相对于直接创建对象,成本比较低。来看obtain()方法的实现

 /**
     * 从线程池中取消息对象
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

要注意,如果消息池是空,那这个方法还是会调用构造方法去创建一个新对象。

既然是循环利用的,那用完了肯定是要回收的。从Hander的整个流程来考虑这个问题,首先,加入到MessageQueue之前是不可能被回收的,在里面的时候也不可能被回收,一般来讲,应该是处理完了这个消息之后把它回收。从过程上来讲是这样的,但是recycle()方法其实不是在Handler里面调用的,而是在Looper.loop()中调用。loop()方法里面先调用了dispatchMessage()去处理这个消息,处理完之后会调用recycle();

recycle()方法完成了这个过程。

   public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

回收之后,就不能再使用这个对象了。所谓回收就是把数据全部清除。

void recycleUnchecked() {
        // 回收过程中还是标记为使用状态
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            //消息池的大小小于最大容量时才会回收
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

同时,在MessageQueue中的消息,或者是正被发送给Handler的消息是不能被回收的。这个池定义了一个最大容量,是50。

关于Message的构造其实还涉及到一个常见的设计模式——享元模式。这里的消息池其实并不是Map之类的实现,而是链表。来看Message的几个字段

 private static final Object sPoolSync = new Object();  //用来获取同步锁
    private static Message sPool;   //sPool其实就是一个Message,所以
    private static int sPoolSize = 0;
Message next;   //next也是Message,这就很明显的可以看出来是链表了
    private static final int MAX_POOL_SIZE = 50;

二、Handler

1.Handler是什么?

Handler允许你发送和处理与线程的MessageQueue相关联的MessageRunnable任务每个Handler实例与一个线程和该线程的消息队列相关联。当你创建一个新的Handler时,它就被绑定到创建它的那个线程和该线程的消息队列,从这个时候开始,它就可以给message queue发送消息,或者处理从message queue中取出的消息。

2.Handelr有什么用?

Handler有两个主要的作用:1.对message和runnable任务进行调度,控制它们在将来的某一个时间点执行。2.将任务切换到不同的线程去执行。

经典的比如,有时候需要进行复杂的操作,网络请求、数据库操作等等,需要到子线程去执行。执行完成之后,可能需要更新UI,但是Android是不允许在子线程中进行UI操作的,所以必须切换到主线程中去执行,这就需要使用到消息机制,也就是通过Handler把这个任务切换到子线程中去执行。

重要的是Handler可以处理两种东西,一种是Message,一种是Runnable任务。对于Runnable任务的处理,就是执行它的回调run()方法,对于Message,通过重写的handleMessage()来处理。

当一个应用的进程被创建的时候,主线程的main()方法里面其实就维护了一个Looper,这个Looper不断的轮询,就是通过Looper的轮询取出Message Queue里面的消息,根据不同的消息来处理四大组件的声明周期。

3.Handler的创建

直接通过new Hander()就可以创建一个Handler对象了。

但是,在这之前,创建handler所在的线程必须要有Looper的。文档中已经说过,每一个Handler的实例是和一个线程绑定起来的,也就和这个线程的Looper绑定起来了,如果当前线程没有创建Looper,也就没有MessageQueue,那消息就没有地方发了,所以当前线程的这个handler就没法接收消息,就会抛异常了。

Handler的无参构造会调用Handler(Callback callback,boolean sync)方法。下面是这个方法中的代码。

  public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

这个方法有两个参数,这里传的callback是用来处理消息的,一般为空,还有一个boolean表示是不是异步的,true表示异步。默认情况下,Handler是同步的,除非构造函数传了true。如果是异步的,Handler会调用Message.setAsynchronous(boolean)来给每个要发送给它的Message进行设置。

可以看到,这里需要通过Looper.myLooper()来获取mlooper的值,然后设置Handler实例内部的message queue的引用。真正需要的是MessageQueue。来看Looper.myLooper()这个方法的内容

    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

通过一个ThreadLocal对象get()方法返回当前线程的Looper,如果没有调用过prepare()方法这个方法就会返回空。所以我们需要先调用prepare初始化Looper。ThreadLocal这个类提供了线程局部变量。

// sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

来接着看上面提到的Handler的构造方法,mQueue = mLooper.mQueue;。我们来看Looper的构造方法。

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

很明显,在Looper的构造函数里面,与之相关联的MessageQueue就被初始化出来了。当前线程也被关联起来了。

Each Handler instance is associated with a single thread and that thread’s message queue.

所以我们来看,每一个Handler实例会与单个线程和它的MessageQueue关联起来。从这里来看,其实是每一个Handler会与Looper产生关联。为什么会需要Looper呢?因为它需要在Looper中定义的MessageQueue,而MessageQueue的初始化是在Looper的构造函数中进行的。

所以到这里就可以看到,每一个线程、Handler实例、Looper实例、MessageQueue这些都是关联的,一一对应的。Looper已经做了把线程、MessageQueue绑定起来的工作,所以Handler其实只需要和Looper绑定起来就和其他的也绑定起来了。

当然,我们产生Looper并不是直接通过构造函数,而是调用Looper.prepare()方法。

    public static void prepare() {
        prepare(true);
    }

    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));
    }

实际上也就是通过ThreadLocal的set方法设置一个Looper,其实还是用到了构造函数。构造Looper的时候可以设置它是否允许退出,所谓的退出其实是针对MessageQueue的,因为looper.quit(boolean)方法其实就是调用了queue.quit(boolean)方法。这里的quitAllowed设置也是设置给MessageQueue的,但是我们一般不会自己去构造一个MessageQueue,调用Looper.prepare的时候它自动会去创建和它关联的MessageQueue。

我们来总结一下,一个Handler对象的诞生过程。首先,通过Looper.myLooper方法来获取当前线程的Looper对象,这个方法又会去调用ThreadLocal.get()来取得线程相关的Looper。如果之前Looper.prepare()没有被调用,那就返回了null,就会抛异常了。如果已经被调用了,然后,MessageQueue也被关联起来。

事件处理

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

Looper.loop()里面会调用这个方法,会根据Message有没有设置Callback来决定处理方式,如果是Callback就直接回调它的run方法,如果是普通的message就调用handlMessage方法来处理。

三、Looper

与线程绑定的进行消息循环的类。

除了主线程,用户自己创建的线程默认是没有初始化这个类的。需要通过调用prepare()来初始化,然后通过loop()来启动工作,最后调用quit()退出。大多数消息循环的交互其实是通过Handler来进行的。官方给出了一个Looper Thread的示例。

 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();
        }
    }

此类包含在MessageQueue上设置和管理事件循环所需的代码。但是,影响队列状态的APIs应该被定义在MessageQueue或者是Handler中。

这里着重来看一下loop()这个方法,这是Looper的具体运行机制所在。

    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;

        // 确认当前线程是本地线程,因为Message是可以跨进程工作的
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

      //所谓的loop的重点就是在这里,死循环,只能从内部跳出。
        for (;;) {
            Message msg = queue.next(); // 这里可能会阻塞
            if (msg == null) {
                //消息队列清空了才会退出
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
              //重点在这里,把消息拿去分发,Message的Target就是一个Handler
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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();
        }
    }

先是验证Looper,然后从looper中取出相应的message queue。(然后是Binder的方法,暂时不太清楚)接下来就开始了具体的操作了,这是一个for的死循环,在循环里面不断的从message queue中取出消息,如果消息为空了,就退出。这里也是作为出口。

looper.quit()方法调用后其实就是从这里退出,所谓的quit其实就是清空消息队列。最后,对消息做了回收。在介绍Message的时候已经说过了,既然消息池的操作,肯定是要有回收,这里就执行了这个操作。

四、MessageQueue

MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
  //本地方法调用
        mPtr = nativeInit();
    }

MessageQueue的构造很简单,一个退出标志和一个本地方法调用参数。一般不会调用MessageQueue的构造方法来自己构造实例,Looper会自动构建一个。

来看MessageQueue的重要方法next()

essage next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // 获取当前时间
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                  //取出来的消息不是立即发送的,如果当前时间还没有到指定的发送时间,就要继续等待
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                      //取出这个消息
                        return msg;
                    }
                } else {
                    nextPollTimeoutMillis = -1;
                }

                if (mQuitting) {
                    dispose();
                    return null;
                }

                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }
插入
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

五、ThreadLocal

这个是Java用来保证线程安全的一个类,每个ThreadLocal变量都是线程私有的,它是支持 泛型的。

public void set(T value) {
        //先获取当前线程
        Thread t = Thread.currentThread();
        //根据当前线程得到map
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

把当前线程的那个值设置给一个key,传进来的参数就是当前线程的本地量。这是一种key,value的存储形式,但是有些特殊,先拿到当前线程,然后通过当前线程得到这个线程里面的ThreadLocalMap,这个ThreadLocalMap是Therad类的一个成员。既然是map形式的,肯定就有key和value,但是要注意,这里的key是很特殊的,它是这个ThreadLocal本身,值就是传进来 的value。

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

六、整体流程分析

1.初始化Looper

首先,Handler的创建需要Looper的支持,因为Handler需要获取到当前线程的MessageQueue。而MessageQueue说到底其实是Looper的一个成员,为了获得MessageQueue,所以我们需要初始化Looper。Looper的初始化是调用Looper.prepare()来完成的。

初始化了Looper,也就初始化了MessageQueue,同时也获取了当前线程。还有一点要注意,handler初始化的时候,这里有一个callback也是执行了初始化的。

2.创建Handler

直接new 一个Handler就OK了,默认它是与创建它所在的线程绑定的。一般来讲,new Handler的时候会重写handleMessage方法。

3.开始循环

调用Looper.loop()方法。这个方法就会开始for死循环,内部通过messageQueue.next()不断取出消息,

4.发送消息

从使用方式上说,其实Handler的发送消息有两种,一种是post(Runnable),一种是sendMessage(Message),从根本上来说,Runnable方式其实还是把Runnable封装到Message里面,然后在dispatchMessage方法中做判断,如果有这个Runnable,就直接调用run()方法,没有就调用handleMessage处理消息。

5.退出

looper.quit(),就退出了

这个方法具体是调用了enqueMessage(queue,msg,uptimeMills)

实际的插入队列操作是由message queue的enqueueMessage(msg,uptimeMills)来完成的。

boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

消息插入队列之后,接下来就是Looper的工作了。Looper.loop()不断从队列循环取出消息,交给Handler去处理。

 /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

            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循环里面,如果消息队列为空了,这个循环就从内部退出了。

最后,这个方法调用了recycleUnchecked()对Message进行了回收。

还有一个点msg.target.dispatchMessage(msg)这个函数是对取出的消息进行分发的,这是Handler内部的方法。

/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

这里是通过callback来判断怎么处理这个消息的。在Message.obtain的方法中是有可选参数来指定callback这个参数的,但是一般默认的无参构造是没有指定这个 数据的。在Handler的构造方法中,也是有指定这个参数的选项的。实际上最后都是要重写handleMessage()方法来指定处理方式的。

最后来看一看主线程的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.prepareMainLooper()这个方法,其实跟Looper.prepare()是一样的,主要是看这个逻辑和代码的执行顺序。先初始化了Looper,其实内部也初始化了MessageQueue,关联了当前线程。然后就是主线程Handler的初始化了,最后,就是调用loop()方法进行不断的循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值