1, activity of the Runonuithread
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 ();
The android Activity Runonuithread () method uses2, 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.handl EMessage (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 {Th Read.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 {Th Read.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 () } catch (Interr Uptedexception e) { e.printstacktrace (); } Textview.post (New Runnable () { @Override public void Run () { textview.settext ("UI updated");} ) ; } }). Start ();
Summarize:
1, in fact, the above four ways can be attributed to one way: handler used for communication between Android threads.
2. Why does Android require UI manipulation only on the UI thread? The main thing is to avoid the problem of concurrency caused by multithreading. The UI is secure in a single-threaded operation.
Several ways Android updates the UI