Why is it possible on Android 5 (Lollipop) to directly change UI views from other threads?

試著忘記壹切 提交于 2019-12-05 07:25:09

It's a matter of timing, for example inserting your code in onCreate() would not crash the app on Samsung Galaxy S3 nor Nexus 7 2013 on Android 5.1. However, if you modify the code such that it's constantly updating the TextView:

    new Thread() {
        @Override
        public void run() {
            int count = 0;
            while (true) {
                SystemClock.sleep(16);
                ((TextView) findViewById(R.id.test)).setText(count++ + "");
            }
        }
    }.start();

Then it'll crash on ~18th call, when TextView.setText(String) inadvertently calls View.requestLayout(); which eventually calls ViewRootImpl.requestLayout() that actually does check for correct thread. This is probably done to reduce the overhead of thread checking to a minimum.

What I have noticed so far, If you create a new thread in an Activity, the code compiles and runs without and error.

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    new Thread() {
        @Override
        public void run() {
            txtName.setText("Some text");
        }
    }.start();

}

but if you create a new thread in a service or asynctask, it causes the CalledFromWrongThreadException exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!