Sub thread to update main thread (UI)
Main thread: A has hander. handlemessage () to process the "MSG" from subthread B;
Sub thread: B use hander. sendmessage (MSG) to main thread;
1 import Java. util. timer; 2 Import Java. util. timertask; 3 Import android. app. activity; 4 Import android. OS. bundle; 5 import android. OS. handler; 6 Import android. OS. message; 7 public class handlerdemo extends activity {8 9 // Title provides variables for the settitle method. For convenience, I have set this variable to int type 10 private int title = 0; 11 private handler mhandler = new handler () {12 public void handlemessage (Message MSG) {13 switch (MSG. what) {14 Case 1: 15 updatetitle (); 16 break; 17} 18}; 19}; 20 public void oncreate (bundle savedinstancestate) {21 super. oncreate (savedinstancestate); 22 setcontentview (R. layout. main); 23 24 timer = new timer (); 25 timer. scheduleatfixedrate (New mytask (), 1, 5000); 26} 27 28 private class mytask extends timertask {29 @ override 30 public void run () {31 // handle the event 32 message = new message (); 33 Message. what = 1; 34 mhandler. sendmessage (Message); 35 36} 37} 38 39 40 public void updatetitle () {41 42 settitle ("welcome to Mr Wei's blog" + title ); 43 title ++; 44} 45}
Sub thread to update main thread (UI)