Android Timer Usage

Source: Internet
Author: User

Android, with thread safety in mind, does not allow UI threads to be executed in threads, and in Android, there is a class: Android.os.Handler, which enables message delivery between threads everywhere. First look at the segment code, this instantiation of a handler,handler can communicate through a message on multiple threads, which is done in a timed Reclen plus 1, and then in a certain format, displayed on the Rectime (UI thread action).
1FinalHandler Handler=NewHandler () {
2PublicvoidHandlemessage (Message msg) {
3Switch(msg.what) {
4Case1:
5Reclen++;
6Rectime.settext (Getrectime (Reclen));
7Break;
8}
9 Super. Handlemessage (msg);
Ten }
one };
The following is an instantiation of a timertask, which is to provide a timer to execute the content. The addition of this method is to give handler a Send Message function, because this in the timer thread, cannot directly manipulate the UI thread.1TimerTask Task=NewTimerTask () {
2PublicvoidRun () {
3Message message=NewMessage ();
4Message.what= 1;
5      handler.sendmessage (message);     
6    }  
7 };   Add a timer to get the program up and running1Timer=NewTimer (True);
2Timer.schedule (Task,1000,1000);//Delay 1000ms after execution, 1000ms execution once
3 //timer.cancel ();  // exit 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.