Android Timer usage, androidtimer

Source: Internet
Author: User

Android Timer usage, androidtimer

Timer properties: http://www.apihome.cn/api/java/Timer.html

Statement creation:

1 private Timer mTimer; 2 3 protected void onCreate (Bundle savedInstanceState) {5 super. onCreate (savedInstanceState); 6 this. setContentView (R. layout. main); 7 8 timer = new Timer (); 9 timer. schedule (task, 1000,500 0); 11} 13 14 TimerTask task = new TimerTask () {15 @ Override 16 public void run () {18 Message message = new Message (); 20 message. what = 1; 22 handler. sendMessage (message); 24} 26}; 27 28 fin Al Handler handler = new Handler () {30 public void handleMessage (Message msg) {32 switch (msg. what) {34 case 1: 36 log. e ("Timer", "Timer"); 38 // code of the function to be implemented: update (); 40 break; 42} 44 super. handleMessage (msg); 46} 48}; 49 50 protected void onDestroy () {52 if (timer! = Null) {54 timer. cancel (); 56 timer = null; 58} 60 super. onDestroy (); 62}

The most important thing is that timer. schedule (task, 5000) does not work if it is set to timer. schedule (task.
Because timer. schedule (task, 5000) indicates the task to be executed once.
Timer. schedule (task,) indicates that the recurrence of execution starts 5 seconds after 1 second

1 private Handler handler = new Handler (); 2 3 private Runnable runnable = new Runnable () {4 5 public void run () {6 7 update (); 8 9 handler. postDelayed (this, 1000); // The postDelayed (this, 1000) method schedules a Runnable object to the main thread queue for 10 11} 12 13}; 14 15 handler. postDelayed (runnable, 1000); // start Timer16 17 handler. removeCallbacks (runnable); // stop Timer

(

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.