Android-interaction instance (clock) between sub-thread and main thread)
The. xml Code is as follows:
The. java program code is as follows:
Package org. lxh. demo; import java. util. date; import java. text. simpleDateFormat; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. textView; public class Hello extends Activity {private TextView info = null; private static final int SET = 1; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case SET: Hello.this.info. setText ("current time:" + msg. obj. toString (); break ;}}; private class ClockThread implements Runnable {// Thread class that displays time public void run () {while (true) {try {Message msg = Hello. this. handler. obtainMessage (Hello. SET, new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "). format (new Date (); Hello. this. handler. sendMessage (msg); Thread. sleep (1000);} catch (Exception e) {}}} public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // life cycle method super. setContentView (R. layout. main); // set the layout manager this.info = (TextView) super. findViewById (R.id.info); new Thread (new ClockThread ()). start (); // start thread }}
The running instance is as follows: