Android Timer TimerTask, Timer, Handler, androidtimertask
Android Timer TimerTask and Timer. to update the UI of the main thread in TimerTask, since the Android programming model does not allow updating the UI of the main thread in a non-main thread, therefore, you need to update the main thread UI in Java's TimerTask by using Android Handler.
A simple example is provided. The Code uses standard Java TimerTask and Timer to start a Timer Task. This task updates the UI of the main thread every 2 seconds (the latest System time is displayed in the TextView of the main thread: System. currentTimeMillis ()).
1 import java. util. timer; 2 import java. util. timerTask; 3 4 import android. OS. bundle; 5 import android. OS. handler; 6 import android. OS. message; 7 import android. app. activity; 8 import android. widget. textView; 9 10 public class MainActivity extends Activity {11 12 private Timer timer; 13 private TimerTask task; 14 15 @ Override16 protected void onCreate (Bundle savedInstanceState) {17 super. onCreate (sav EdInstanceState); 18 setContentView (R. layout. activity_main); 19 20 final TextView TV = (TextView) findViewById (R. id. textView); 21 22 final int WHAT = 102; 23 final Handler handler = new Handler () {24 @ Override25 public void handleMessage (Message msg) {26 switch (msg. what) {27 case WHAT: 28 TV. setText (msg. obj + ""); 29 break; 30} 31} 32}; 33 34 task = new TimerTask () {35 @ Override36 public void run () {37 Message message = new Message (); 38 message. what = WHAT; 39 message. obj = System. currentTimeMillis (); 40 handler. sendMessage (message); 41} 42}; 43 44 timer = new Timer (); 45 // parameter: 46/1000, executed after 1 second delay. 47 // 2000, the task is executed every 2 seconds. 48 timer. schedule (task, 1000,200 0); 49} 50 51 @ Override52 protected void onStop () {53 super. onStop (); 54 55 // pause 56 // timer. cancel (); 57 // task. cancel (); 58} 59}