Handler延时消息的实现机制

本文深入剖析Handler如何实现延迟消息。从sendMessage方法开始,详细解释sendMessageDelayed的逻辑,包括messageQueue的enqueueMessage方法和Looper的next方法。重点讨论了nativiePollOnce方法中的epoll_wait机制,阐述了I/O多路复用在Android主线程消息循环中的作用,解释了为何Looper.loop()的死循环不会阻塞主线程。
摘要由CSDN通过智能技术生成

Handler是如何实现延迟消息的?针对这个问题,我们从源码的角度来剖析一下Handler延时消息的实现逻辑.

handler核心的发送消息的方法是sendMessage,有的朋友会说那post呢?

PS:post的话其实算是一个handler的语法糖,传入runnable后帮助我们构建一个message

/**
     * 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(Runnable r)
    {
   
       return  sendMessageDelayed(getPostMessage(r), 0);
    }


    private static Message getPostMessage(Runnable r) {
   
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

可以看到getPostMessage里帮我们构建出一个message然后再调用sendMessageDelayed。

接下来看sendMessage,类似于startActivity最终都会走到startActivityForResult一样,handler所有发送消息的方法最终都会走到sendMessageDelayed,只是delayMillis不同而已,这个delayMillis就是延时的时间。

/**
     * Pushes a message onto the end of the message queue after all pending messages
     * before the current time. It will be received in {@link #handleMessage},
     * in the thread attached to this handler.
     *  
     * @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 sendMessage(Message msg)
    {
   
        return sendMessageDelayed(msg, 0);
    }
    
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
   
        if (delayMillis < 0) {
   
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

然后这里会将DelayMillis加上当前开机的时间(这里可以理解就是这个time就是,现在的时间+需要延迟的时间=实际执行的时间),接下来进到sendMessageAtTime方法里面

/**
     * 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>
     * Time spent in de
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值