Android Timer Timertask,timer, to update the main thread UI in TimerTask, since the Android programming model does not allow the main thread UI to be updated in a non-main thread, It is therefore necessary to update the main thread UI in Java's timertask with the handler implementation of Android.
Now gives a simple example. The code uses standard Java TimerTask and the timer to start a timer task. The task updates the UI of the main thread every 2 seconds (TextView on the main thread shows the latest system time: System.currenttimemillis ()).
Package Zhangphil.timertask;import Java.util.timer;import Java.util.timertask;import android.os.bundle;import Android.os.handler;import Android.os.message;import Android.app.activity;import Android.widget.TextView;public Class Mainactivity extends Activity {private Timer timer;private timertask task; @Overrideprotected void OnCreate (Bundle s Avedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); final TextView TV = ( TextView) Findviewbyid (R.id.textview); final int what = 102;final Handler Handler = new Handler () {@Overridepublic void Han Dlemessage (Message msg) {switch (msg.what) {case WHAT:tv.setText (msg.obj + ""); task = new TimerTask () {@Overridepublic void run () {Message message = new Message (); message.what = What;message.obj = Syst Em.currenttimemillis (); handler.sendmessage (message);}; Timer = new timer ();//parameter://1000, delay 1 seconds after execution. 2000, perform 1 tasks every 2 seconds. Timer.schedule (Task, 1000, 2000);} @Overrideprotected void OnStop () {super.onstop ();//pause//TImer.cancel ();//Task.cancel ();}}
Android Timer Timertask,timer,handler