Android消息机制不彻底解析(上)


    Handler和Message是Android开发者经常使用的两个API,我一直对于它的内部实现比较好奇,因此用空闲的时间,阅读了一下他们的源码。

   相关的Java Class:
  • android.os.Message
  • android.os.MessageQueue
  • android.os.Looper
  • android.os.Handler
    相关的C++ Class:
  • android.NativeMessageQueue
  • android.Looper
  • android.LooperCallback
  • android.SimpleLooperCallback
  • android.Message
  • android.MessageHandler

首先,来看看这些类之间的关系:java

 


首先,让咱们从相对简单的java实现开始看起:android

 

Message

    Message类能够说是最简单的,主要提供了一些成员,用以保存消息数据。
    public int what;//用以表示消息类别

    public int arg1;//消息数据

    public int arg2;//消息数据

    public Object obj;//消息数据
    
    /*package*/ long when;//消息应该被处理的时间
    
    /*package*/ Bundle data;//消息数据
    
    /*package*/ Handler target;//处理这个消息的handler
    
    /*package*/ Runnable callback;//回调函数
    
    // sometimes we store linked lists of these things
    /*package*/ Message next;//造成链表,保存Message实例

    值得一提的是,Android提供了一个简单,可是有用的消息池,对于Message这种使用频繁的类型,能够有效的减小内存申请和释放的次数,提升性能。
    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;

    private static final int MAX_POOL_SIZE = 50;

    /**
     * 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;
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

    /**
     * Return a Message instance to the global pool.  You MUST NOT touch
     * the Message after calling this function -- it has effectively been
     * freed.
     */
    public void recycle() {
        clearForRecycle();

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {//消息池大小未满,则放入消息池
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
    /*package*/ void clearForRecycle() {
        flags = 0;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        when = 0;
        target = null;
        callback = null;
        data = null;
    }

    小结:
  1. Message的核心在于它的数据域,Handler根据这些内容来识别和处理消息
  2. 应该使用Message.obtain(或者Handler.obtainMessage)函数获取message实例

 

Handler

    首先看看构造函数:app

 

    public interface Callback {
        public boolean handleMessage(Message msg);
    }

 

    public Handler() {
        this(null, false);
    }
    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; //使用Callback能够拦截Handler处理消息,以后会在dispatchMessage函数中,大展身手
        mAsynchronous = async;//设置handler的消息为异步消息,暂时先无视这个变量
    }

    Handler的构造函数最主要的就是初始化成员变量:mLooper和mQueue。 这边须要注意的一个问题是:Looper.myLooper()不能返回null,不然抛出RuntimeExeception。稍后详解Looper.myLooper();函数在何种状况下会抛出异常。less


    Handler.obtainMessage系列的函数都会调用Message类中对应的静态方法,从消息池中获取一个可用的消息实例。典型实现以下:异步

    public final Message obtainMessage()
    {
        return Message.obtain(this);
    }

 


    Handler.post系列和send系列函数最终都会调用enqueueMessage函数,把message入列,不一样之处在于post系列函数会以Runable参数构建一个Message实例。async

 

     private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;//一会咱们会看到callback非空的message和callback为空的mesage在处理时的差别
        return m;
    }

    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

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

    //最终都会调用这个函数,把message入列
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);//Handler的mAsynchronous属性,决定了msg是否为asynchronous,稍后在MessageQueue.next函数中,能够看到asynchronous对于消息处理的影响        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

    除了这些以外,Handler还提供了hasMessage系列和removeMessages系列函数用以管理Handler对应的MessageQueue中的消息。ide

 


    接下来主角登场,Handler.dispatchMessage:函数

 

    private static void handleCallback(Message message) {
        message.callback.run();
    }
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }
    
    /**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {//message的callback不为null,则执行
            handleCallback(msg);
        } else {
            if (mCallback != null) {//若是Hanlder的mCallback成员不为null,则调用
                if (mCallback.handleMessage(msg)) {//若是handleMessage返回值为true,则拦截消息
                    return;
                }
            }
            handleMessage(msg);//处理消息
        }
    }

    注释应该比较清楚,很少说。 小结:oop

  1.  Handler类最为核心的函数是enqueueMessage和dispatcherMessage,前者把待处理的消息放入MessageQueue,而Looper调用后者来处理从MessageQueue获取的消息。
  2.  callback不为null(经过post系列函数添加到消息队列中)的message没法被拦截,而callback为null的函数能够被Handler的mCallback拦截

 


Looper

    一样从构造函数看起:
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);//每一个Looper有一个MessageQueue
        mRun = true;
        mThread = Thread.currentThread();
    }
     ** 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);//后台线程的looper都容许退出
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");//每一个线程只能有一个Looper
        }
        sThreadLocal.set(new Looper(quitAllowed));//把实例保存到TLS(Thread Local Save),仅有每一个线程访问本身的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.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);//主线程的lopper不能够退出
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }
    由于是私有的构造函数,因此理论上来讲只能经过prepare和prepareMainLooper两个函数来实例化Looper,可是google的注释也说的很清楚:prepareMainLooper()应该由系统调用(有兴趣的同窗能够去看看AtivityThread类的main函数),因此,应用开发者可使用的只剩下prepare函数。
    好了,Looper的实例是构造出来,可是如何获取构造出来的实例呢?
    /** Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }
    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static Looper myLooper() {
        return sThreadLocal.get();
    }
     如今,咱们应该知道如何防止Handler实例化的时候,抛出RuntimeException:在守护线程中实例化Handler以前,须要先调用Looper.perpare函数来构造Looper实例。

     而后,重头戏来了: 
    /**
     * Quits the looper.
     *
     * Causes the {@link #loop} method to terminate as soon as possible.
     */
    public void quit() {
        mQueue.quit();
    }

    /**
     * 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) {//调用looper以前,须要先调用perpare,不然您懂的...
            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 获取一个下一个消息,若是当前没有要处理的消息,则block,以后咱们会看到这个API的实现
            if (msg == null) {//调用了MessgeQueu的quit函数后,MessageQueue.next会返回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
            Printer logging = me.mLogging;
            if (logging != null) {//借助logging咱们能够打印Looper中处理的消息
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);//调用handler处理消息

            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.recycle();//回收消息到消息池
        }
    }
    Looper.loop()函数是Looper类的核心函数,主要循环进行两个操做:
  1. 从MessageQueue中获取一个消息,当前没有消息须要处理时,则block
  2. 调用message的Handler(target)处理消息
    基本上,咱们能够把Looper理解为一个死循环,Looper开始work之后,线程就进入了以消息为驱动的工做模型。

    小结:
  1. 每一个线程最多能够有一个Looper。
  2. 每一个Looper有且仅有一个MessageQueue
  3. 每一个Handler关联一个MessageQueue,由该MessageQueue关联的Looper执行(调用Hanlder.dispatchMessage)
  4. 每一个MessageQueue能够关联任意多个Handler
  5. Looper API的调用顺序:Looper.prepare >> Looper.loop >> Looper.quit
  6. Looper的核心函数是Looper.loop,通常loop不会返回,直到线程退出,因此须要线程完成某个work时,请发送消息给Message(或者说Handler)

MessageQueue

    
    MessageQueue类是惟一包含native函数的类,咱们先大体看一下,稍后C++的部分在详细解释:
    private native void nativeInit();    //初始化
    private native void nativeDestroy(); //销毁
    private native void nativePollOnce(int ptr, int timeoutMillis); //等待timeoutMillis指定的时间
    private native void nativeWake(int ptr);//唤醒nativePollOnce的等待

    而后,咱们再从构造函数看起:
    
    Message mMessages;//数据域mMessages的类型虽然是Message,可是由于Message.next数据域的缘由,其实mMessage是链表的第一个元素

    MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        nativeInit();//初始化nativeMessageQueue
    }
    对应的,在销毁的时候:
    @Override
    protected void finalize() throws Throwable {
        try {
            nativeDestroy();//销毁nativeMessageQueue
        } finally {
            super.finalize();
        }
    }
    
    此外,MessageQueue提供了一组函数(e.g. hasMessage, removeMessage)来查询和移除待处理的消息,咱们在前面的Handler类上看到的对应函数的实现就是调用这组函数。

    接下来,看看enqueueMessage函数,Handler函数就是调用这个函数把message放到MessageQueue中:
    final boolean enqueueMessage(Message msg, long when) {
        if (msg.isInUse()) {//检查msg是否在使用中,一会咱们能够看到MessageQueue.next()在返回前经过Message.makeInUse函数设置msg为使用状态,而咱们以前看到过Looper.loop中经过调用调用Message.recycle(),把Message重置为未使用的状态。
            throw new AndroidRuntimeException(msg + " This message is already in use.");
        }
        if (msg.target == null) {//msg必须知道由那个Handler负责处理它
            throw new AndroidRuntimeException("Message must have a target.");
        }

        boolean needWake;
        synchronized (this) {
            if (mQuiting) {//若是已经调用MessageQueue.quit,那么再也不接收新的Message
                RuntimeException e = new RuntimeException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            }

            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {//插到列表头
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;//当前MessageQueue处于block状态,因此须要唤醒
            } 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();//当且仅当MessageQueue由于Sync Barrier而block,而且msg为异步消息时,唤醒。 关于msg.isAsyncChronous(),请回去看看Handler.enqueueMessage函数和构造函数
                Message prev;
                for (;;) {// 根据when的大小顺序,插入到合适的位置
                    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;
            }
        }
        if (needWake) {
            nativeWake(mPtr);//唤醒nativeMessageQueue
        }
        return true;
    }
 
    final void quit() {
        if (!mQuitAllowed) {//UI线程的Looper消息队列不可退出
            throw new RuntimeException("Main thread not allowed to quit.");
        }


        synchronized (this) {
            if (mQuiting) {
                return;
            }
            mQuiting = true;
        }
        nativeWake(mPtr);//唤醒nativeMessageQueue
    }
    关于sync barrier,再补充点解释: sync barrier是起到了一个阻塞器的做用,它能够阻塞when>它(即执行时间比它晚)的同步消息的执行,但不影响异步消息。sync barrier的特征是targe为null,因此它只能被remove,没法被执行。MessageQueue提供了下面两个函数来控制MessageQueue中的sync barrier(如何以为sync barrier和异步消息难以理解的话,选择性无视就好,由于它们不妨碍咱们理解Android消息机制的原理):
    final int enqueueSyncBarrier(long when) {
        // Enqueue a new sync barrier token.
        // We don't need to wake the queue because the purpose of a barrier is to stall it.
        synchronized (this) {
            final int token = mNextBarrierToken++;
            final Message msg = Message.obtain();
            msg.arg1 = token;

            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

    final void removeSyncBarrier(int token) {
        // Remove a sync barrier token from the queue.
        // If the queue is no longer stalled by a barrier then wake it.
        final boolean needWake;
        synchronized (this) {
            Message prev = null;
            Message p = mMessages;
            while (p != null && (p.target != null || p.arg1 != token)) {
                prev = p;
                p = p.next;
            }
            if (p == null) {
                throw new IllegalStateException("The specified message queue synchronization "
                        + " barrier token has not been posted or has already been removed.");
            }
            if (prev != null) {
                prev.next = p.next;
                needWake = false;
            } else {
                mMessages = p.next;
                needWake = mMessages == null || mMessages.target != null;//其实我以为这边应该是needWake = mMessages != null && mMessages.target != null
            }
            p.recycle();
        }
        if (needWake) {
            nativeWake(mPtr);//有须要的话,唤醒nativeMessageQueue
        }
    }

    重头戏又来了:
  final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();//不太理解,选择性无视
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);//等待nativeMessageQueue返回,最多等待nextPollTimeoutMillis毫秒

            synchronized (this) {
                if (mQuiting) {//若是要退出,则返回null
                    return null;
                }

                // 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) {//下一个消息为sync barrier
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());//由于存在sync barrier,仅有异步消息能够执行,因此寻在最近的异步消息
                }
                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);//消息还没到执行的时间,因此咱们继续等待msg.when - now毫秒
                    } else {
                        // Got a message.
                        mBlocked = false;//开始处理消息了,因此再也不是blocked状态
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;//从链表中间移除message
                        } else {
                            mMessages = msg.next;//从链表头移除message
                        }
                        msg.next = null;
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
                        msg.markInUse();//标记msg正在使用
                        return msg;//返回到Looper.loop函数
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;//没有消息能够处理,因此无限制的等待
                }

                // 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)) {// 目前无消息能够处理,能够执行IdleHandler
                    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("MessageQueue", "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;//Looper.looper调用一次MessageQueue.next(),只容许调用一轮IdleHandler

            // 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;//由于执行IdleHandler的过程当中,可能有新的消息到来,因此把等待时间设置为0
        }
    }
              为了方便你们理解Message的工做原理,先简单描述nativeWake,和natePollonce的做用:
  1. nativePollOnce(mPtr, nextPollTimeoutMillis);暂时无视mPtr参数,阻塞等待nextPollTimeoutMillis毫秒的时间返回,与Object.wait(long timeout)类似
  2. nativeWake(mPtr);暂时无视mPtr参数,唤醒等待的nativePollOnce函数返回的线程,从这个角度解释nativePollOnce函数应该是最多等待nextPollTimeoutMillis毫秒

    小结:
  1. MessageQueue做为一个容器,保存了全部待执行的消息。
  2. MessageQueue中的Message包含三种类型:普通的同步消息,Sync barrier(target = null),异步消息(isAsynchronous() = true)。
  3. MessageQueue的核心函数为enqueueMessage和next,前者用于向容器内添加Message,而Looper经过后者从MessageQueue中获取消息,并实现无消息状况下的等待。
  4. MessageQueue把Android消息机制的Java实现和C++实现联系起来。
    原本我是想一口气把java实现和C++实现都写完的,可是,无奈最近工做和我的事务都比较多,稍后为你们奉上C++实现的解析。
相关文章
相关标签/搜索