Why on Android 5 (Lollipop) can I directly change the appearance of the user interface from other threads?

Consider the following code:

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

On pre-Lollipop androids, this code throws a CalledFromWrongThreadException exception, but why does it work fine on Lollipop androids?

Test environment: Genymotion emulator is running Android 5.1

The code was inside the onCreateView() method of the Fragment class.

+6
source share
2 answers

This is a matter of time, for example, inserting code in onCreate () will not cause the application to crash on Samsung Galaxy S3 or Nexus 7 2013 on Android 5.1. However, if you change the code so that it constantly updates 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 will hit the 18th call when TextView.setText(String) inadvertently calls View.requestLayout(); which ultimately calls ViewRootImpl.requestLayout() , which really checks for the correct thread. This is probably done to minimize the overhead of checking threads.

+3
source

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

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 throws a CalledFromWrongThreadException.

+1
source

Source: https://habr.com/ru/post/986370/


All Articles