Android消息机制

Android消息机制

消息机制模型

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

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

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

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

一、Message

消息一般来说都包含相应的操作描述,可能还携带一些数据。Message类是实现了Parcelable接口。一个Message一般包含以下这些内容。

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

Message的创建有两种方法:

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

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

 /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

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

既然是循环利用的,那用完了肯定是要回收的。recycle()方法完成了这个过程。

/**
     * Return a Message instance to the global pool.
     * <p>
     * You MUST NOT touch the Message after calling this function because it has
     * effectively been freed.  It is an error to recycle a message that is currently
     * enqueued or that is in the process of being delivered to a Handler.
     * </p>
     */
    public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

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

二、Handler

1.Handler是什么?

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

2.Handelr有什么用?

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

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

3.Handler的创建

直接通过new Hander()就可以创建一个Handler对象了。但是,在这之前,创建handler所在的线程必须要有looper的。如果当前线程没有looper,这个handler就没法接收消息,就会抛异常了。Handler的无参构造会调用Handler(Callback callback,boolean sync)方法。下面是这个方法中的一些代码

 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;

可以看到,这里通过Looper.myLooper()来获取mlooper的值。来看Looper.myLooper()这个方法的内容

 /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

通过一个ThreadLocal对象get()方法返回当前线程的Looper,如果没有就返回空。ThreadLocal这个类提供了线程局部变量。这里具体的ThreadLocal类的介绍稍后再说。

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

sThreadLocal声明在Looper类中,这里已经很明确的说清楚了,如果没有调用prepare()方法,这个get()就会返回空。prepare()方法就是用来初始化Looper的了。这个方法稍后再表。

来接着看上面提到的Handler的构造方法,mQueue = mLooper.mQueue;在确认完looper存在后, 就获取跟Looper关联的MessageQueue。我们来看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的构造函数中进行的。

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

/** 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 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,其实还是用到了构造函数。

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

三、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的具体运行机制所在。

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

先是验证Looper,然后从looper中取出相应的message queue。(然后是Binder的方法,暂时不太清楚)接下来就开始了具体的操作了,这是一个for的死循环,在循环里面不断的从message queue中取出消息,如果消息为空了,就退出。这里也是作为出口。当looper.quit()方法调用后其实就是从这里退出。最后,对消息做了回收。在介绍Message的时候已经说过了,既然消息池的操作,肯定是要有回收,这里就执行了这个操作。

四、MessageQueue

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

MessageQueue的构造很简单,一个退出标志和一个本地方法调用参数。

来看MessageQueue的重要方法next()

essage next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        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) {
                // Try to retrieve the next message.  Return if found.
                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 {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                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);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            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;
    }

五、整体流程分析

我们先来从Handler的创建开始。下面是Handler的构造函数的一部分。

 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;

首先,Handler的创建需要Looper的支持,因为Handler需要获取到当前线程的MessageQueue。而MessageQueue这个东西说到底其实是Looper的一个成员,为了获得MessageQueue,所以我们需要初始化Looper。Looper的初始化时调用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));
    }

这里有一个参数确定当前Looper能不能退出。我们平时使用完后,是需要调用quit()来退出的,但是主线程的Looper是不需要退出的。通过ThreadLocal来将Looper和当前线程关联起来了。

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

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

MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }

到这里,我们需要的Handler,Looper和MessageQueue的创建已经全部完成了。

然后,既然是消息机制,肯定要有需要处理的消息。消息从哪里来?可以直接new Message(),更好的方法是调用Message.obtain()或者是Handler.obtainMessage()Handler.obtainMessage的这个方法其实就是对obtain()的封装,只是默认指定了当前的Handler作为targer属性。

/**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    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();
    }

从消息池池返回消息。显然,这种方法明显是更好的。当然了,如果最开始没有Message对象,其实也是会直接New的。消息池的消息虽然让你拿出来用了,但是你用完了肯定是要给我收回去重复利用的。注意的是,既然是回收,肯定是要用完了再回收,不可能还没用就被回收了。

需要注意,消息是有目的地的,即它要交给哪个Handler去处理,通过它的taget属性来指定。这里这个无参的obtain是没有指定target的。当然,也可以调用有参构造obtain(handler h)来设置。

通常我们还需要对拿到的Message调用一些set方法去设置一些参数。

既然消息拿到了,接下来就要把消息送到消息队列里面去了。有三个问题,由谁来送?怎么送?送到哪里去?

首先,是由Handler来送进去的。它通过调用sendMessage()这一类的方法来把消息送到队列里面去,其实都是归根到底都是调用sendMessageAtTime(Message msg,long uptimeMills)来发送。

/**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {@link #handleMessage}, in the thread attached
     * to this handler.
     * 
     * @param uptimeMillis The absolute time at which the message should be
     *         delivered, using the
     *         {@link android.os.SystemClock#uptimeMillis} time-base.
     *         
     * @return Returns true if the message was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }

看这个方法的第一行,解释了刚才提到的第三个问题。我们前面已经说过,在New Handler的时候,当前线程的MessageQueue就与之绑定了,所以Handler也只能送到它自己的关联的那个MessageQueue里面去

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

 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

注意我们上面提到的Message是有目的地的,在obtain()的过程中其实是没有指定这个属性的。这里就为我们指定了这个属性,就是当前的Handelr,就是发送这个Message的Handler。同时,也说明了,是谁发的就由谁来处理。

实际的插入队列操作是由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()方法进行不断的循环。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值