Android 消息机制流程浅析

2021-06-22  本文已影响0人  黎明来了

Android消息机制分析:

Android的消息机制主要是指Handler的运行机制,Handler的运行需要由Loop,MessageQueuen,Message来支持。

作用:Android开发规范中,不能在子线程中更新UI,当我们做完耗时操作的时候需要更新UI,这时候就需要使用Handler机制。

大致流程:

Handler发送消息到MessageQueuen中,然后通过Looper.loop()启用死循环从MassageQueuen#next()取出消息,再分发给Messsage的目标Handler进行处理消息。

Handler:发送消息和处理消息分别对应Handler中的两个函数

Handler#enqueueMessage(Message msg) 压入到MessageQueuen

Handler#handleMessage(Message msg) 处理消息

Runable和Message被Hander"压入"到MessageQueuen中

Looper循环地去取出消息交给Hander处理

Handler的初始化

Handler发送消息的函数:

获取到Handler或它的子类的实例,

//构造方法
public Handler() {
        this(null, false);
    }
//
public Handler(@Nullable 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());
            }
        }
       //通过静态方法获取到Looer实例
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        //获取到MessageQueuen
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;//异步调用
    }
    //不支持App调用,只提供给系统使用
    @UnsupportedAppUsage
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

上面的代码块是Handler的可使用的构造方法中的其中两个,在构造方法中获取Looper的静态方法获取到Looper对象,如果Looper为null,就会抛出异常。接着会对MessageQueuen、CallBack、Asynchronous赋值.构造方法主要的任务就是初始化和赋值

Looper.java
 /**  返回当前线程的Looper对象
     * 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() {
       //将会返回空,除非你调用了Looper.prepare()
        return sThreadLocal.get();
    }

通过Looper的静态方法myLooper方法,可以看到,如果sThreadLocal存在Looper实例就会返回Looper实例,否则就会返回null,并没有在这个函数中实例化Looper对象。在Handler中的构造方法中有Looper是否为空的检查,当myLooper为null就会抛出异常,所以要在初始化Handler之前实例化Looper对象,并保存在当前线程。

Looper.java
/** 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));
    }
  //quitAllowed:是否运行退出
  private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

从prepare函数可以得出每个线程只有一个Looper实例并且创建的Looper对象保存在当前线程的ThreadLocal中;在看Looper的构造方法,在它的构造方法中初始化了MessageQueue实例,而且获取到了当前线程。

总结:

  1. 初始化Handler对象之前,必须调用 Looper.prepare()确保Looper对象已经创建。

  2. 每一个线程最多有一个Looper对象,每个Looper对象有且只有一个MessageQueue.

消息发送

Handler消息发送相应功能的函数声明如下:

post系列

final boolean post(Runnable r);
final boolean postAtTime(Runable, long);
final boolean postDelayed(Runnable, long);
final boolean postAtFrontOfQueue( Runnable r)

send系列

final boolean sendEmptyMessage(int what);
final boolean sendEmptyMessageDelayed(int what, long delayMillis);
final boolean sendEmptyMessageAtTime(int what, long uptimeMillis);/*以上只发送包含what值的消息*/
final boolean sendMessage(Message msg);
final boolean sendMessageAtFrontOfQueue(Message msg);
final boolean sendMessageAtTime(Message msg, long uptimeMillis);
final boolean sendMessageAtFrontOfQueue(Message msg);
final boolean sendMessageDelayed(Message msg, long delayMillis);

现在将这两个系列的函数作为线索来分析Handler的消息发送的流程。

先从post系列入手:

Handler.java
 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean post(@NonNull Runnable r) {
       //实际上post系列内部也是调用的send系列函数
       return  sendMessageDelayed(getPostMessage(r), 0);
    } 
  public final boolean postAtTime(@NonNull Runnable r, long uptimeMillis) {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }
  public final boolean postDelayed(@NonNull Runnable r, long delayMillis) {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }
  //将Runnable包装成Message
  private static Message getPostMessage(Runnable r) {
        //获取Message实例
        Message m = Message.obtain();
        m.callback = r;//将Runnabled对象设置为message的回调函数
        return m;
    }

分析post系列可以得出,它们将其他类型“零散”的信息转化成Message,然后在调用send系列的函数,所以接下来我们重点来分析send系列的函数。

Handler.java
   /**
     * Sends a Message containing only the what value.
     *  
     * @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.
     */
    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }  
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
   public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis/*延迟该时间分发*/) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
  
  public boolean sendMessageAtTime(@NonNull 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);
    }

通过上面的代码块,我们可以得出结论:无论post系列还是send系列函数,最终都交给 sendMessageAtTime()函数进行放入队列的操作。咱们接着分析这个入队列的操作

Handler.java
 private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        //将当前Handler设置给Message的target
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();/**只给系统服务使用*/
        //是否异步
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //将message放入到MessageQueuen
        return queue.enqueueMessage(msg, uptimeMillis);
    }

在Handler的enqueueMessage函数中将handler实例设置给Message的target,然后将入队列的操作交给MessageQueuen。好了,在Handler中的发送消息的流程已经结束了,现在我们去分析Message是怎样进入MessageQueuen的

MessageQueuen.java
boolean enqueueMessage(Message msg, long when) {
        //首先判断,是否有处理该Message的handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //Message是否在已经使用
        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();//将Message设置为已经使用
            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;
    }

分析以上代码,可以看出实际上MessageQueuen维护的是一个链表结构,enqueueMessage实际上将message放入到链表中,根据时间来决定就message放入到哪个位置。这一部分分析完Handler从发送消息到入队的过程。

处理消息

现在发送的消息已经保存到MessageQueuen中了,现在需要将MessageQueuen按规则取出来,我们已经知道Looper在消息机制中负责将MessageQueuen中的message取出并且分发出去,所以查看Looper中的方法,可以看到其中静态函数Loop就是完成相应功能的函数。

所以要想消息机制运行起来,得在创建完Handler实例后,调用Looper.Loop()函数

Looper.java
   /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        //获取到Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //取出Looper所对应的MessageQueue
        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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {/*开启死循环*/
            Message msg = queue.next(); // might block 可能会阻塞,调用Message.next方法取出Message
            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);
            }
            // Make sure the observer won't change while processing a transaction.
            final Observer observer = sObserver;

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            Object token = null;
            if (observer != null) {
                token = observer.messageDispatchStarting();
            }
            long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
            try {
               //开始分发给Message所属的Handler消息
                msg.target.dispatchMessage(msg);
                if (observer != null) {
                    observer.messageDispatched(token, msg);
                }
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } catch (Exception exception) {
                if (observer != null) {
                    observer.dispatchingThrewException(token, msg, exception);
                }
                throw exception;
            } finally {
                ThreadLocalWorkSource.restore(origWorkSource);
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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.recycleUnchecked();
        }
    }

Looper开启一个死循环,不断地通过MessageQueuen.next取出消息,然后交给msg.target处理,让我们来看看MessageQueuen.next做了什么?

MessageQueuen.java
Message 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
        //下一个轮询超时 Millis
        int nextPollTimeoutMillis = 0;
        for (;;) {/*开启一个死循环*/
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //jni
            nativePollOnce(ptr, nextPollTimeoutMillis);
            //开始检索下一条message,找到就返回
            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) {/*taget为空*/
                    // 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.获取以一个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.
                   //没有message设置为-1
                    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;
        }
    }

首先,在MessageQueuen.next()中开启了一个死循环,当有message时且不大于当前时间返回当前头节点,如果message.when大于当前时间,就会设置一个超时然后唤醒循环。

现在重新回到Looper.loop函数,将取出的message交给当前它的Handler来分发处理

Handler.java
    /*
     * Handle system messages here.
     *  开始分发
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {/*如果callback不为空,也就是设置了runnable*/
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
         
            handleMessage(msg);
        }
    }
 private static void handleCallback(Message message) {
        message.callback.run();
    }

到这里Handler的从发送Message到处理消息就处理完毕了!

上一篇 下一篇

猜你喜欢

热点阅读