Android主线程的消息系统(Handler\Looper)(3)

/**
    * Enqueue a message into the message queue after all pending messages
    * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
    * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
    * You will receive it in {@link #handleMessage}, in the thread attached
    * to this handler.
    *
    * @param uptimeMillis The absolute time at which the message should be
    *        delivered, using the
    *        {@link android.os.SystemClock#uptimeMillis} time-base.
    *       
    * @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.  Note that a
    *        result of true does not mean the message will be processed -- if
    *        the looper is quit before the delivery time of the message
    *        occurs then the message will be dropped.
    */
    public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;//注意这行代码后面会用,把Handler赋值给Msg的target对象
            sent = queue.enqueueMessage(msg, uptimeMillis);//把msg放到MsgQueue中
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }

上面的方法第二个是延时毫秒数,queue.enqueueMessage把消息发送到MessageQueue后剩下的就是等待消息被处理,前面不是说了Looper.loop()方法开始轮询消息队列吗,你发送的消息就是在loop方法中读取到的,读取到后谁去处理呢?在loop()方法中有一句代码:

msg.target.dispatchMessage(msg);

msg就是你发送到MessageQueue的消息,被读取后调用target.dispatchMessage(),这个target就是上面Handler发送消息是赋值的,就是发送消息的Handler本身,然后Handler调用自己的下面方法就行消息处理:

/**
    * Handle system messages here.
    */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);//在这会调用到上面重写的handleMessage方法。
        }
    }

因为在new Message的时候callback为空,并且Handler的mCallback = null,所以会调用到你上面new Handler时重写的handleMessage方法。

总结:

每一个线程中都对应一个Looper,每一个Looper都对应一个MessageQueue,这个Looper是用来管理消息队列的,主要是读取消息队列和把消息发送给Message的target去处理。到这你应该清除Thread、Handler、Message、MessageQueue和Looper他们之间的关系了吧。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/bea06878edc58d744cabe120d1c4c232.html