05.Handler源码之Message的创建与发送

132 阅读4分钟

这篇我们来看看Message的创建和发送。

Message的创建

Message可以通过构造方法直接创建,也可以通过obtain()函数从全局消息池获取。

obtain()方法的注释:

Return a new Message instance from the global pool. Allows us to avoid allocating new objects in many cases.

val message1=Message()    //直接创建
val message2=Message.obtain()    //从线程池返回
val message3=Message.obtain(handler)    //和handler进行绑定
val message4=handler.obtainMessage()    //等价于message3,最终也是调用Message.obtain()

除了message1是直接创建的,其他都是从消息池获取的。

使用obtain()方法可以省去创建对象的开销,直接从全局的消息对象池返回一个现成的对象(有则直接返回,无则创建)。

obtain()方法有多个重载:

  • obtain(Message orig):复制orig的属性值,包括其handler

  • obtain(Handler h):为Message绑定Handler

  • obtain(Handler h, Runnable callback):绑定Handler和回调方法

  • Message obtain(Handler h, int what):绑定handler并传入参数

  • obtain(Handler h, int what, Object obj)

  • obtain(Handler h, int what, int arg1, int arg2)

  • obtain(Handler h, int what, int arg1, int arg2, Object obj)

还可以调用handler.obtainMessage()创建Message,该方法调用了Message.obtain(Handler h)方法,直接绑定当前handler,该消息可以直接调用sendToTarget()进行发送。

Message发送

已绑定Handler的Message可以直接调用message.sendToTarget()发送消息,该方法其实调用了绑定的Handler的sendMessage(message)方法。

如果Message没有和具体的Handler绑定,需要调用handler.sendMessage(message)发送。该方法会先调用sendMessageDelayed(@NonNull Message msg, long delayMillis),最终调用到Handler的sendMessageAtTime(@NonNull Message msg, long uptimeMillis),源码如下:

public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;    //延时时间大于等于0
        }
        //消息的发送时间=当前时间+延时时间
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;    //mQueue是handler初始化时Looper传进来的消息队列
        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;    //target指向当前Handler进行绑定
        msg.workSourceUid = ThreadLocalWorkSource.getUid();    //设置Uid

        if (mAsynchronous) {    //Handler初始化时传入的参数,默认为false
            msg.setAsynchronous(true);    //将消息设置为异步,将不受同步屏障影响,直接插队处理
        }
        return queue.enqueueMessage(msg, uptimeMillis);    //将当前消息添加到消息队列尾部
    }

//调用MessageQueue的入队方法,将消息插入消息队列
boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {    //此处是Handler空异常处理
            throw new IllegalArgumentException("Message must have a target.");
        }

        synchronized (this) {
            if (msg.isInUse()) {    //判断消息是否正在使用
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            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;    //p指向消息队列的队头
            boolean needWake;    //是否唤醒事件队列
            if (p == null || when == 0 || when < p.when) {    //当消息队列为空,或者Message的发送时间小于队头的发送时间,则将事件插入到消息队列头部
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;    //mBlocked默认为false,当调用了next()方法,消息队列中没有消息且没有可运行的空闲处理程序,会设置mBlocked=true
            } 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;    //返回值代表是否将消息插入队列,不表示消息会得到处理
    }

消息发送后,会在Handler的发送方法内对消息队列进行判空处理,再将消息和Handler进行绑定。接着调用消息队列的入队方法,首先会对Handler进行空判断,然后寻找合适的位置进行入队操作。

消息队列是单向链表,以消息的发送时间进行增序排序,当队头为空或者消息的发送时间小于队头发送时间时直接插入到队头。

当消息成功加入消息队列后,会返回true,但此返回结果不代表消息会得到处理。