Android Timer Timertask,timer,handler

Source: Internet
Author: User

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

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.