View.post(Runnable ) 与postDelayed - 浅析

一、View.post(Runnable )

源码
    /**
     * <p>Causes the Runnable to be added to the message queue.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action 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.
     *
     * @see #postDelayed
     * @see #removeCallbacks
     */
    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

View.post(Runnable ) 是干啥的呢??官方说:

  • 将Runnable添加到消息队列。
  • runnable将在UI线程上运行。
  • 如果这会UI线程闲着,就直接帮你干活
  • 如果这会正忙,那就给你排个队等着吧

在细节点,就是在post(Runnable)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象post到Handler里。
在Handler里,它将传递过来的action对象包装成一个Message(Message的callback为action),然后将其投入UI线程的消息循环中。
在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnable的run方法。而此时,在UI线程里,就可以来更新UI了。

示例:
       new WebView(this).post(new Runnable() {
            @Override
            public void run() {
                //你要在主线程做的事情
            }
        });

二、postDelayed (Runnable action, long delayMillis)

    new WebView(this).postDelayed(new Runnable() {
        @Override
        public void run() {
            //1秒后你要在主线程做的事情
                
        }
    },1000);

这哥们啥意思呢?就是可以让你延时1秒再做事情,其他和上面那货一毛一样啊,不信我们看看源码:

   public boolean postDelayed(Runnable action, long delayMillis) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.postDelayed(action, delayMillis);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().postDelayed(action, delayMillis);
        return true;
    }
注意

由于不是在新的线程中使用,所以千万别做复杂的计算逻辑。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值