android_runOnUIThread

效果图:

点击runOnUiThread按钮 跳转到runOnUi界面中去 延时3秒刷新图片

layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_run_on_ui"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iamchan.allfunction.ui.widget.RunOnUiActivity">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include layout="@layout/toolbar"></include>
        <ImageView
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</RelativeLayout>

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没错了

猜你喜欢

转载自blog.csdn.net/iamchan/article/details/83619903
今日推荐