美文网首页
Android 消息机制之Handler

Android 消息机制之Handler

作者: CodeDuan | 来源:发表于2021-03-11 17:57 被阅读0次

    在Android中,Android的消息机制多指Handler的运行机制,在Handler的运行过程中,Message,MessageQueue,Looper也是必不可少的一部分,接下来我们简单分析它们的工作过程。

    一、Message

    Message顾名思义就是消息的意思,他是Handler发送消息的载体。接下来我们来看Message中常用的几个参数。

    /**
    * User-defined message code so that the recipient can identify
    * what this message is about. Each {@link Handler} has its own name-space
    * for message codes, so you do not need to worry about yours conflicting
    * with other handlers.
    */
    public int what;
     /**
    * arg1 and arg2 are lower-cost alternatives to using
    * {@link #setData(Bundle) setData()} if you only need to store a
    * few integer values.
    */
    public int arg1;
     /**
    * arg1 and arg2 are lower-cost alternatives to using
    * {@link #setData(Bundle) setData()} if you only need to store a
    * few integer values.
    */
    public int arg2;
    /**
    * An arbitrary object to send to the recipient.  When using
    * {@link Messenger} to send the message across processes this can only
     * be non-null if it contains a Parcelable of a framework class (not one
    * implemented by the application).   For other data transfer use
    * {@link #setData}.
    */
    public Object obj;
    

    根据源码中的注释我们可以知道各个参数的含义;
    what:用户定义的消息代码,以便接收人识别此消息的含义,简单来说就是标识符。
    agr1/2:存储整型数值。
    obj:发送的对象。

    另外注释中还提到,setData方法。

    public void setData(Bundle data) {
            this.data = data;
        }
    

    通过setData方法,我们可以利用Bundle传递更多我们想要的参数。

    1.1 Message的创建:
    通常没阅读过源码的人都会通过new Message的方法来构造Message对象,但是我们来看源码。

    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
        public Message() {
        }
    
    /**
    * 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的首选方法是通过Message.obtain(); 此方法是从全局池中返回一个新的Message实例,避免了Message的重复创建。

    二、MessageQueue
    MessageQueue指的是消息队列,主要负责插入消息(enqueueMessage)和读取消息(next)。

    2.1 插入消息
    MessageQueue.enqueueMessage

    boolean enqueueMessage(Message msg, long when) {
            //如果target为空  target指的就是Handler 
            if (msg.target == null) {
                throw new IllegalArgumentException("Message must have a target.");
            }
    
            synchronized (this) {
                //如果msg已经在使用
                if (msg.isInUse()) {
                    throw new IllegalStateException(msg + " This message is already in use.");
                }
                //如果退出 回收msg
                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的使用状态
                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;
        }
    

    2.2 读取消息
    MessageQueue.next

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

    MessageQueue是何时创建的呢?接下来我们看Looper;

    三、Looper
    Looper翻译为循环的意思,主要作用为不停的从MessageQueue中查看是否有新消息,如果有则会处理,否则会一直阻塞。首先看一下Looper的构造方法。

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

    其中的mQueue指的就是MessageQueue,这恰好回答了我们上面的问题:MessageQueue是在创建Looper时创建的。

    3.1 Looper的创建。
    那么Looper又是何时创建的呢? 我们先来看Handler的源码。

    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());
                }
            }
    
            mLooper = Looper.myLooper();
            if (mLooper == null) {
                throw new RuntimeException(
                    "Can't create handler inside thread " + Thread.currentThread()
                            + " that has not called Looper.prepare()");
            }
            mQueue = mLooper.mQueue;
            mCallback = callback;
            mAsynchronous = async;
        }
    

    看源码中抛出的异常是不是很熟悉? 翻译为:不能在线程内创建Handler,还没有调用Looper.prepare()。
    再加上面的 if (mLooper == null) 我们大概就可以知道,我们需要通过Looper.prepare()创建Looper。接下来继续看Looper的源码;

        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);
            mThread = Thread.currentThread();
        }
    

    通过Looper.prepare()方法,最后调用到了prepare(boolean quitAllowed)中的sThreadLocal.set(new Looper(quitAllowed));此时Looper就已经创建。如果我们在子线程中使用Handler,则必须先调用Looper.prepare()创建Looper。

    3.2 Looper的启动。
    其实Looper中最重要的是loop方法,只有调用了loop();消息循环才会生效,这也是为什么我们在子线程中使用Handler时,需要同时调用Looper.prepare()和Looper.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.");
            }
            if (me.mInLoop) {
                Slog.w(TAG, "Loop again would have the queued messages be executed"
                        + " before this one completed.");
            }
    
            me.mInLoop = true;
            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
                if (msg == null) {//如果msg为空 跳出
                    // 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 {
                    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();
            }
        }
    

    可以看到,loop()方法是一个死循环,即一直都在循环消息,当MessageQueue的next方法返回的msg为null的时候才会跳出这个循环。
    当我们调用Looper.quit方法时,就会调用MessageQueue的quit,此MessageQueue被标记为退出状态,next方法则返回为null。Looper才会退出。关键源码如下:

    Looper.java
    public void quit() {
            mQueue.quit(false);
        }
    
    public void quitSafely() {
            mQueue.quit(true);
        }
    
    MessageQueue.java
    void quit(boolean safe) {
            if (!mQuitAllowed) {
                throw new IllegalStateException("Main thread not allowed to quit.");
            }
    
            synchronized (this) {
                if (mQuitting) {
                    return;
                }
                mQuitting = true; //标记为退出
    
                if (safe) {
                    removeAllFutureMessagesLocked();
                } else {
                    removeAllMessagesLocked();
                }
    
                // We can assume mPtr != 0 because mQuitting was previously false.
                nativeWake(mPtr);
            }
        }
    MessageQueue.java next()方法
           if (mQuitting) {
                dispose();
                return null;
            }
    

    所以说,当我们不在需要使用Handler时,需要调用Looper.quit来退出Looper,否则Looper.loop和MessageQueue.next均会阻塞。

    到这里也会读者会问到,为什么子线程中需要调用Looper.prepare和Looper.loop,而主线程中却不用呢?
    我们可以看到Looper中有这样一段代码。

    /**
         * Initialize the current thread as a looper, marking it as an
         * application's main looper. See also: {@link #prepare()}
         *
         * @deprecated The main looper for your application is created by the Android environment,
         *   so you should never need to call this function yourself.
         */
        @Deprecated
        public static void prepareMainLooper() {
            prepare(false);
            synchronized (Looper.class) {
                if (sMainLooper != null) {
                    throw new IllegalStateException("The main Looper has already been prepared.");
                }
                sMainLooper = myLooper();
            }
        }
    

    注释中提到:应用程序的主循环程序是由Android环境创建的,所以你无须调用它。那么prepareMainLooper()究竟是在哪里调用了呢? 我们通过查到引用。可以查到是在ActivityThread中的Main方法中调用的。部分代码如下:

     public static void main(String[] args) {
            Looper.prepareMainLooper();
            Looper.loop();
        }
    

    由此可以判断出,ActivityThread就是我们APP的主线程了,且内部自动创建了Looper,而且主线程中的Looper不可退出。

    至此,我们知道如果没有消息则会阻塞,如果有消息会怎样处理呢?我们来看loop方法中关键的一行代码。

    msg.target.dispatchMessage(msg);
    

    其中msg.target指的就是Handler,我们继续看Handler的dispatchMessage方法。

    public void dispatchMessage(@NonNull Message msg) {
            if (msg.callback != null) {
                //如果callback不为空 则调用handleCallback
                handleCallback(msg);
            } else {
                //如果mCallback不为空 则调用handlerMessage来处理消息
                if (mCallback != null) {
                    //如果为true 则return
                    if (mCallback.handleMessage(msg)) {
                        return;
                    }
                }
                //如果mCallback为空 则调用Handler的handler方法
                handleMessage(msg);
            }
        }
    

    其中msg.callback是一个Runnable对象,实际上就是Handler的post方法传递的Runnable。
    mCallback是一个接口,包含了 handleMessage方法。所以我们可以通过new Handler(Callback)的方式来创建一个Handler。

    四、Handler工作原理
    Handler的工作主要为发送消息和接收消息。通过一系列的send和post方法来实现发送消息。

    图1 图2

    就拿sendMessage来举例,我们先看下源码:

    public final boolean sendMessage(@NonNull Message msg) {
            return sendMessageDelayed(msg, 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);
        }
    
    private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
                long uptimeMillis) {
            msg.target = this;
            msg.workSourceUid = ThreadLocalWorkSource.getUid();
    
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
    

    可以看到 最后还是调用了MessageQueue的enqueueMessage方法,也就是将这条消息插入到了队列中。再结合上面我们所认识的MessageQueue和Looper大致也就搞清楚Handler的工作原理了;大致如下:

    Handler通过调用send/post等一系列方法,将Message插入到MessageQueue中,此时Looper通过MessageQueue的next方法拿到Message,当Looper拿到Message后,通过调用msg.target即Handler的dispatchMessage(msg)方法来处理消息。最终通过handleCallback或Handler的handleMessage将Message的处理交给开发者,这样大致就是整个Handler的运行机制了。

    如果有哪里不对的地方,欢迎各位指正交流。一起进步。

    相关文章

      网友评论

          本文标题:Android 消息机制之Handler

          本文链接:https://www.haomeiwen.com/subject/wlznqltx.html