Android消息机制三剑客之Handler、Looper、Message源码分析(二)

版权声明:本文为博主原创文章,转载请注明出处,谢谢。 https://blog.csdn.net/sdsxtianshi/article/details/81207571

Android消息机制:
Android消息机制三剑客之Handler、Looper、Message源码分析(一)
Android消息机制三剑客之Handler、Looper、Message源码分析(二)

消息通信机制的运行原理

    上一篇中,单独分析了Handler、Looper、MessageQueue,本篇就分析一下这三者是如何协同工作,实现线程间通信的。我们就以Looper类中官方给出的子线程中经典通信样例来分析分析每步都做了什么。

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

    首先,在线程中先调用了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));
    }

    ... ...

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

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

    prepare方法为当前线程初始化通信环境,每个线程只能持有一个Looper实例,并且通过set将Looper实例与本地线程绑定。而在Lopper的构造函数中,又创建了MessageQueue的实例,这里也就为当前线程准备好了MessageQueue来接收Message对象,而在MessageQueue的构造函数中调用的是Native层的初始化方法,创建一个单向链表的队列,对Native层有兴趣的朋友可以自行分析,这里就不再深入了。
    接下来mHandler = new Handler() {…}创建了Handler的实例,并重写了handleMessage,也就是消息通信的终点,那么我们来看看Handler的构造方法:

    public Handler() {
        this(null, false);
    }

   //空构造最终调用了下面的构造方法

   /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with represent to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    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;
    }

    这里带着注释来看还是因为注释里告诉了我们很多信息,之前就有面试官问道Handler是不是同步的? 当时一下懵住了,没有想过这个问题,但答案其实在注释里已经告诉我们了,这里就不再对注释进行翻译,大家可以自行看一下。在Handler的构造方法里可以看到分别拿到了Looper和Message的实例,mLooper和mQueue,在这里三剑客也就聚齐了。
    运行到这里,当前线程下的消息通信环境已经搭建完成,接下来Looper.loop()才是重头戏,为线程开启了消息循环,从这里开始,消息通信开始运行起来:

/**
     * 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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

    loop()方法中核心就是开启了无限循环,这其中,我们需要仔细研究的是这三个关键方法:

  • queue.next():从MessageQueue中取出下一个Message,在MessageQueue中执行一次出队操作;
  • msg.target.dispatchMessage(msg) :将取出的Message对象分发给绑定的Handler;
  • msg.recycle() : 回收该Message实例,存入global pool,后续可以通过msg.obtain()在global pool中直接获取Message实例,避免了每次都创建新的实例;

     首先看一下next()方法的内部实现:

final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);

            synchronized (this) {
                if (mQuiting) {
                    return null;
                }

                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;      /** mMessage是该链表队列的头结点 **/
                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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } 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)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

            ... ...

           }//(sync)
        }//(for)
    }

     next()方法中核心逻辑也是一个无限循环,目的就是返回下一个要处理的消息,然后从消息队列中进行出队。其中mMessages保存的是队列的头结点,从该节点开始向下遍历。首先进行判空处理,在msg非空但target为空时表示这是一个异步消息,是否异步是在Handler构造时进行定义的,默认情况下都是同步的,因此这里的逻辑一般不会执行。
    接着向下,判断当前时间是否到达msg指定的发送时间,因为消息入队时会根据携带的发送时间进行排序,在未达到发送时间时,msg不出队,而是设置nextPollTimeoutMillis,这个变量有什么用呢,我们回到循环最开始的地方,这里在nextPollTimeoutMillis 非0时,调用flushPendingCommands挂起当前线程,该方法预示系统后续可能会有长时间的线程block到来,也就是最后一部分,在当前线程挂起(两种情况:初始消息队列为空 或 msg需要在未来某时处理)后会取出idelHandler(闲置Handler,如果存在的话)进行处理。如果这时候连idelHandler也不存在的话,线程进入阻塞,continue直接无限循环,直到找到需要处理的msg。
    那么找到msg后,因为默认都是同步msg,这里prevMsg为空,走else,将mMessage头结点指针向下移动,然后msg出队,添加已用标记,return返回msg,这样Looper.loop()方法中的Message msg = queue.next()这条语句执行完毕 ,拿到要进行分发的Message对象,那么接下来就是执行msg.target.dispatchMessage(msg); 进行消息分发,这里调用到的是Handler中的方法:

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

    dispatchMessage方法很简单,我们在创建Handler实例的时候使用的空构造,因此这里的callback为null,也就是直接调用了handleMessage,也就是在创建时候我们重写的handleMessage方法了,至此消息得到处理,Message对象完成了一次通信,在loop()中最后调用recycle()方法,将Message实例回收,可以通过obtain再次获取到该实例,而不必每次都新建实例了。
    至此,我们通过一个官方简单示例分析了整个消息通信的框架,现在我们再根据流程图总体回顾一下:
这里写图片描述
    在本地线程中,首先必须先调用Looper.prepare()方法,该方法会创建号Looper实例和MessageQueue实例,然后再创建Hanlder实例,并重写handlerMessage方法,自定义消息处理,在Handler的构造方法中,会引入Looper和MessageQueue实例。然后调用Looper.loop()开启无限循环,不断的调用next()从消息队列中取出消息,如果消息队列为空或未到消息处理时间时,线程进入阻塞状态。而在外部,调用Handler的send/post系列方法后,最终都调用SendMessageAtTime方法,为msg添加when属性,然后调用Handler内部的enqueueMessage方法,此处为msd绑定target为当前Handler,接着调用到MessageQueue类中定义的enqueueMessage,此方法中将接收的msg进行入队,将mMessages指向队列头部。同时,入队操作还会唤醒已阻塞的线程(如果在阻塞状态的话),接着next()方法就可以取到该入队的msg,并调用msg.target.dispatchMessage()方法,最后就调用到了重写的handleMessage()方法,完成了消息通信。

猜你喜欢

转载自blog.csdn.net/sdsxtianshi/article/details/81207571