前面有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有可能已经退出,那么发送的这条消息就会被丢弃。