Android Timer TimerTask, Timer, Handler, androidtimertask

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.