Android updates the UI in several ways. android updates the ui in several ways.
1. runOnUiThread of the Activity
TextView = (TextView) findViewById (R. id. TV); new Thread (new Runnable () {@ Override public void run () {runOnUiThread (new Runnable () {@ Override public void run () {textView. setText ("updated UI ");}});}}). start ();
Android Activity runOnUiThread () method using 2. Handler sendEmptyMessage ()
Package lib.com. myapplication; import android. OS. handler; import android. OS. message; import android. support. v7.app. appCompatActivity; import android. OS. bundle; import android. widget. textView; public class MainActivity extends AppCompatActivity {private TextView textView; Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); textView. setText ("Ui updated") ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. TV); new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} handler. sendEmptyMessage (2 );}}). start ();}}
3. Handler post ()
Package lib.com. myapplication; import android. OS. bundle; import android. OS. handler; import android. support. v7.app. appCompatActivity; import android. widget. textView; public class MainActivity extends AppCompatActivity {private TextView textView; Handler handler = new Handler (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. TV); new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} handler. post (new Runnable () {@ Override public void run () {textView. setText ("Ui updated ");}});}}). start ();}}
4. view Post ()
TextView = (TextView) findViewById (R. id. TV); new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} textView. post (new Runnable () {@ Override public void run () {textView. setText ("Ui updated ");}});}}). start ();
Summary:
1. In fact, the above four methods can be attributed to one method: handler is used for communication between Android threads.
2. Why does android require UI operations only on the UI thread? This is mainly to avoid the concurrency problem caused by multithreading. It is safe to operate the UI in a single thread.