Android Simple Timer

Source: Internet
Author: User

Timer

1. In Android application development, there are many times to use the timer, and to implement the timer more time to use two classes: Timer, and TimerTask

The 2.API explanation of the timer is:

A simple translation: The timer is used to perform a task in the background process, a separate thread comes back to serve the timer ...

So when the timer is used, his timing is actually executed in another thread, and if you want to operate the UI in the UI thread on a regular basis, you need to use handler .

The 3.API interpretation of TimerTask is:

The task performed by the timer is performed by TimerTask.

4. You may encounter two problems when using the two classes above:

1). When you report this error, the timer is cancel () to cancel (), so the thread of the timer is closed, and you want to use this timer to re-new one, But rarely do timer.cancel () in practice.

  2) when the newspaper TimerTask is scheduled already that you put the previous timertask has been re-used again,

  A timertask through the schedule method after use, not through the schedule method call the second time, want to reuse is not possible, is a disposable supplies.

When you re-want to use this timertask, then you can only regain one instance, preferably written as a class:

Class MyTask extends timertask{@Override public void Run () {//TODO auto-generated method stub//do something}};

  So when you re-use this timertask, you can do this:

task= new MyTask (); Timer.schedule (task, 1000);

For this one-time timer, you can stop it after you've finished using it, and creating a new timer means creating a new thread and destroying it without having to.

Timer.cancel ();  Timer.purge (); timer= null;

Every time I use it,

Timer= new Timer ();

Of course, you can make this timer always exist.
Before you re-new the task, it's best to call

Task.cancel ();
5. Here is a small example:
Mainactivity:
 Public classMainactivityextendsActivity {PrivateButton btn; PrivateTextView tvShow; Private intCount = 10;    Timer timer;    Mytimetask Mtimetask; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Timer=NewTimer (true); TvShow=(TextView) Findviewbyid (r.id.tv_show); BTN=(Button) Findviewbyid (R.ID.BTN); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {mtimetask=NewMytimetask (); Timer.schedule (Mtimetask,0, 1000);    }        }); } Handler Mhandler=NewHandler () { Public voidhandlemessage (Message msg) {Tvshow.settext ("" + count--); if(Count <= 0) {timer.purge ();                Mtimetask.cancel (); Count= 10; Btn.setenabled (true); } Else{btn.setenabled (false); System.out.println ("Still remaining" + count + "seconds"); }            Super. Handlemessage (msg);    };    }; Private classMytimetaskextendsTimerTask {@Override Public voidrun () {Message message=Mhandler.obtainmessage (); Message.what= 0;        Mhandler.sendmessage (message); }    }

XML file: Activity_main

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Tools:context=". Mainactivity " >    <TextViewAndroid:id= "@+id/tv_show"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"Android:layout_margintop= "50DP"Android:text= "Show Time"android:textsize= "25SP" />    <ButtonAndroid:id= "@+id/btn"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:layout_margintop= "10DP"Android:text= "timing Start" /></LinearLayout>

The effect of running:

SOURCE download








Android Simple Timer

Related Article

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.