美文网首页程序员
Handler、Looper、MessageQueue源码解析—

Handler、Looper、MessageQueue源码解析—

作者: windfall_ | 来源:发表于2017-05-14 18:30 被阅读0次


MessageQueue


/**
* Low-level class holding the list of messages to be dispatched by a
* {@link Looper}. Messages are not added directly to a MessageQueue,
* but rather through {@link Handler} objects associated with the Looper.
* You can retrieve the MessageQueue for the current thread with
* {@link Looper#myQueue() Looper.myQueue()}.
*/

Handler时用来发送消息的,调用sendMessageAtTime(),在调用MessageQueue的enqueueMessage(msg, uptimeMillis)方法,把消息插入到MessageQueue中。我们首先来看一下MessageQueue的enqueueMessage方法:

    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的loop()方法中,开启了一个死循环,通过调用MessageQueue的next()方法,不断的取出消息,再交给Handler去处理。

Message msg = queue.next();```

我们来看一下MessageQueue的next()方法:

    Message next() {
        //注释1
        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;
                //注释2
                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());
                }
                //注释3
                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.
                //注释4
                if (mQuitting) {
                    dispose();
                    return null;
                }

    }```

首先看注释1:mPrt==0时返回一个null,mPrt在什么时候为空呢,注意到有一个dispose()方法:

private void dispose() {
    if (mPtr != 0) {
        nativeDestroy(mPtr);
        mPtr = 0;
    }
}```

dispose()方法在哪调用呢,注意到在注释4处,当mQuitting==true时调用dispose()方法。那么mQuitting在哪赋值为true呢:

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

也就是上节我们说到调用Looper中的quit()获得quitSafely()时会赋值为true,MessageQueue退出循环。

再看注释3:Message是一个单向链表,next指向下一个Message。首先会先判断当前时间与Message的时间对比:

//获取从开机到现在的时间
final long now = SystemClock.uptimeMillis();

when = SystemClock.uptimeMillis()+uptimeMillis;```

如果message已经准备好,则返回一个Message对象,并把Message的next指针指向下一个message。

再看注释2:什么时候message的target对象为空,在Handler发送Message时制定了target对象,当message的target对象为空时说明不是由Handler插入进来的,在MessageQueue的源码中找到这样一个方法;

    private int postSyncBarrier(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.markInUse();
            msg.when = when;
            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;
        }
    }```
相当于设置一个消息屏障,如果遇到一个消息屏障,就会不停的循环找到一个异步消息,一般我们使用的都是同步消息,我们可以通过Message的setAsynchronous(true)方法指定为异步消息。

既然有开始循环,那么必定会有退出循环,我们调用Looper的quit()或者quitSafely()方法时实际调用的是MessageQueue的quit方法。quit()和quitSafely()方法的区别在Looper中已经提到了,分别调用了
removeAllMessagesLocked()和removeAllFutureMessagesLocked()方法,现在我们来看一下具体实现:

private void removeAllMessagesLocked() {
    Message p = mMessages;
    while (p != null) {
        Message n = p.next;
        p.recycleUnchecked();
        p = n;
    }
    mMessages = null;
}```

因为Message是一个单向链表,把所有的Message回收掉。

   private void removeAllFutureMessagesLocked() {
       final long now = SystemClock.uptimeMillis();
       Message p = mMessages;
       if (p != null) {
           if (p.when > now) {
               removeAllMessagesLocked();
           } else {
               Message n;
               for (;;) {
                   n = p.next;
                   if (n == null) {
                       return;
                   }
                   if (n.when > now) {
                       break;
                   }
                   p = n;
               }
               p.next = null;
               do {
                   p = n;
                   n = p.next;
                   p.recycleUnchecked();
               } while (n != null);
           }
       }
   }```

当p.when > now时,即又延时的消息全部清空,对于没有延时的消息,通过一个死循环等待Handler处理完再回收。

我们注意到无论是Looper的loop()方法还是MessageQueue的next()方法,都是一个死循环,那么为什么不会造成阻塞或者对CPU有什么消耗上的影响?请参考知乎大神回答:[Android中为什么主线程不会因为Looper.loop()里的死循环卡死?](https://www.zhihu.com/question/34652589)

相关文章

网友评论

    本文标题:Handler、Looper、MessageQueue源码解析—

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