一.Activity的 runOnUiThread
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
bt.setText("哈哈");
}
});
}
}).start();
二.Handler sendEmptyMessage()/sendMessage()
1.首先需要创建Handler对象
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (UPDATE == msg.what){
//更新UI
}
}
};
2.创建子线程进行耗时操作,然后发送message
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE;
message.arg1 = 1;
mHandler.sendMessage(message);
mHandler.sendMessageAtTime(message,1000);
mHandler.sendEmptyMessage(UPDATE);
mHandler.sendEmptyMessageDelayed(UPDATE,10000);
mHandler.sendMessageAtTime(message, SystemClock.uptimeMillis() + 10000);
}
}).start();
三.Handler post()
post方法和sendMessage/sendEmptyMessage的效果一样
如果主线程中,我们只需要开启一个子线程的话,我们可以使用post方法,这样可以省去判断message.what的逻辑。
但如果是多个子线程,则需要使用sendMessage
1.在主线程中首先创建Handler对象
Handler handler = new Handler();
2.开启子线程,耗时操作完毕后,调用handler.post方法
new Thread(new Runnable() {
@Override
public void run() {
//进行耗时操作
handler.post(new Runnable() {
@Override
public void run() {
//更新UI
}
});
}
}).start();
注意:Handler还有一个方法,postDelayed(),延迟发送,传入参数为Runnable对象和延迟时间
四.view Post()
new Thread(new Runnable() {
@Override
public void run() {
rv.postDelayed(new Runnable() {
@Override
public void run() {
//更新UI的操作
}
},5000);
}
}).start();
网友评论