子线程与主线程通信的其他方法概述

前面有2篇博客单独讲解了子线程和主线程之间的通信:Thread-Handler-Message和AsyncTask。实现异步通信还有以下的3种方法:

第一种:runOnUiThread(Runnable action)
此方法是在Activity中定义的,官方文档做的说明是:
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.即:这个方法是要运行在主线程的. 如果当前线程不是主线程,就通过post方法传递给主线程队列执行,如果已经在主线程,就立刻执行。

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

代码示例:比如开辟子线程sleep2s, 之后进入某一个界面:这里可以不用Thread-Handler-Message来处理,直接用runOnUiThread。

new Thread() {
                public void run() {
                    SystemClock.sleep(2000);
                    // 在主线程进入某一界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            enterActivity();
                        }
                    });
                };
            }.start();

第二种:View方法中的post(Runnable action):返回值为true的话,说明action 被成功的添加到消息队列中了(message queue),返回值为false的话处理消息队列的looper退出了。

第三种:View 方法中的postDelayed(Runnable action, long delayMillis)。返回值是boolean.它也是将action 添加到消息队列中,但是是在延迟一定时间之后开始执行。需要注意的是当返回值为true的时候,action不一定会被处理,因为looper有可能已经退出,那么发送的这条消息就会被丢弃。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值