Android Countdown Countdowntimer Little Kee

Source: Internet
Author: User

Android Ultra-Simple Countdown implementation: Countdowntimer

Countdowntimer provided by the system

Check the information when found Countdowntimer This class decisively abandoned the previous countdown procedure


Function:

30 seconds countdown, 1 seconds per interval.


Parameters:

Mc.start (); method start

Mc.cancel (); method end

New Mycountdowntimer (30000, +); The first parameter indicates that the total time is 30000 milliseconds, with an interval of 1000 milliseconds



Directly on the code:

Package Com.example.daojishi;import Android.app.activity;import Android.os.bundle;import Android.os.CountDownTimer ; Import Android.util.log;import android.view.view;import android.widget.textview;import android.widget.Toast;/** * * @author Baozi * * Countdown class Countdowntimer * */public class Mainactivity extends Activity {private Mycountdowntimer Mc;priv ATE TextView TV; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); TV = (TextView) Findviewbyid (r.id.show); mc = new Mycountdowntimer (30000, 1000) ; Mc.start ();} public void OnCancel (view view) {Toast.maketext (Mainactivity.this, "Cancel", Toast.length_long). Show ();// Toast has display time delay mc.cancel ();} public void restart (view view) {Toast.maketext (mainactivity.this, "restart", Toast.length_long). Show ();// Toast has display time delay Mc.start ();} /** * Inherit countdowntimer Guard * * Override method of Parent class OnTick (), OnFinish () */class Mycountdowntimer extends Countdowntimer {/** * * @      Param Millisinfuture *      Represents the total number of milliseconds to count down * * For example millisinfuture=1000 for 1 seconds * * @param countdowninterval * Indicates how many microseconds are called One OnTick method * * For example: countdowninterval = 1000; Represents every 1000 milliseconds called once Ontick () * */public Mycountdowntimer (long millisinfuture, long Countdowninterval) {super (millisinfuture, Countdowninterval);} @Overridepublic void OnFinish () {Tv.settext ("Done");} @Overridepublic void OnTick (Long millisuntilfinished) {log.i ("mainactivity", Millisuntilfinished + ""), Tv.settext (" Countdown ("+ millisuntilfinished/1000 +") ... ");}} ┏┓┏┓//┏┛┻━━━┛┻┓//┃┃//┃━┃//┃┳┛┗┳┃//┃┃//┃┻┃//┃┃//┗━┓┏━┛//┃┃ God beast Bless/ /┃┃ Code No bug! ┃┗━━━┓//┃┣┓//┃┏┛//┗┓┓┏━┳┓┏┛//┃┫┫┃┫┫//┗┻┛┗┻┛

Layout:

<relativelayout xmlns: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:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <textview android:id=" @+id/show "android:layout_width=" Wrap_content "Android : layout_height= "wrap_content" android:text= "@string/hello_world"/> <button android:id= "@+id/button 1 "android:onclick=" OnCancel "android:layout_width=" wrap_content "android:layout_height=" wrap_content "Android:layout_alignleft=" @+id/show "android:layout_below=" @+id/show "android:layout_marginleft=" 50 DP "android:layout_margintop=" 106DP "android:text= "Cancel"/> <button android:id= "@+id/button2" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignleft= "@+id/button1" android:layout_below= "@+id/bu Tton1 "android:layout_margintop=" 63DP "android:onclick=" restart "android:text=" restart "/></rel Ativelayout>


Report:

Countdowntimer Source:

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Android.os;import android.util.log;/** * Schedule a countdown until a time in the future, with * regular notific Ations on intervals along the. * * Example of showing a second countdown in a text field: * * <pre class= "Prettyprint" > * New Countdowntimer (300 (XX) {* * public void OnTick (long millisuntilfinished) {* Mtextfield.settext ("seconds remaining:"+ millisuntilfinished/1000); *} * * public void OnFinish () {* Mtextfield.settext ("done!"); *} *}.start (); * </pre> * The calls to {@link #onTick (long)} is synchronized to this object so, one call to {@link #onTick (Long)}  Won ' t ever occur before the previous * callback is complete. This was only relevant when the implementation of * {@link #onTick (Long)} takes a amount of time to execute that is signif Icant * Compared to the countdown interval.     */public abstract class Countdowntimer {/** * Millis since epoch when alarm should stop.    */private final long mmillisinfuture;    /** * The interval in Millis that the user receives callbacks */private final long mcountdowninterval;    Private long mstoptimeinfuture; /** * @param millisinfuture the number of Millis in the @link #start ()} until the Cou     Ntdown is do and {@link #onFinish ()} * is called. * @param countdowninterval The interval along the "to receive * {@link #onTick (Long)} callbacks.        */Public Countdowntimer (long millisinfuture, long countdowninterval) {mmillisinfuture = Millisinfuture;    Mcountdowninterval = Countdowninterval;     }/** * Cancel the countdown.    */public final void Cancel () {mhandler.removemessages (MSG);     }/** * Start the countdown.            */Public synchronized Final Countdowntimer start () {if (mmillisinfuture <= 0) {onfinish ();        return this;        } mstoptimeinfuture = Systemclock.elapsedrealtime () + mmillisinfuture;        Mhandler.sendmessage (Mhandler.obtainmessage (MSG));    return this;     }/** * Callback fired on regular interval.     * @param millisuntilfinished The amount of time until finished.    */public abstract void OnTick (long millisuntilfinished);     /** * Callback fired when the time was up.    */public abstract void onfinish (); Private static final int MSG = 1; Handles counting down private Handler Mhandler = new Handler () {@Override public void Handlemessage (M Essage msg) {synchronized (countdowntimer.this) {final long millisleft = Mstoptimeinfuture-s                Ystemclock.elapsedrealtime ();                if (millisleft <= 0) {onfinish (); } else if (Millisleft < Mcountdowninterval) {//No tick, just delay until done s                Endmessagedelayed (Obtainmessage (MSG), millisleft);                    } else {Long Lasttickstart = Systemclock.elapsedrealtime ();                    OnTick (Millisleft); Take into account user's OnTick taking time to execute long delay = Lasttickstart + Mcountdowninterv                    Al-systemclock.elapsedrealtime (); Special Case:user ' s OnTick took more than interval to//complete, skip to next intErval while (Delay < 0) delay + = Mcountdowninterval;                Sendmessagedelayed (Obtainmessage (MSG), delay); }            }        }    };}

Daily Fine Top further


Android Countdown Countdowntimer Little Kee

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.