效果图:
点击runOnUiThread按钮 跳转到runOnUi界面中去 延时3秒刷新图片
layout:
java:
public class RunOnUiActivity extends SwipeBackActivity {
@BindView(R.id.iv_imgLeft)
ImageView ivImgLeft;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.img)
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_on_ui);
ButterKnife.bind(this);
initView();
initData();
}
private void initView() {
ivImgLeft.setImageResource(R.drawable.left);
ivImgLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
tvTitle.setText("runOnUI");
}
private void initData() {
/*
*
* 模拟一个耗时操作
* 耗时操作不能放在UI线程中执行 ANR
*
* 但是子线程不能更新UI
*
*
* UI线程不能进行耗时操作
* 子线程不能进行更新UI
*
*
* */
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
runOnUiThread(new Runnable() {
@Override
public void run() {
img.setImageResource(R.mipmap.iamchan);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
查看runOnUiThread源代码
是handler没错了