Android has encapsulated an abstract class Countdowntimer for us to implement the timer function:
/*** Countdown Timer*/ PrivateCountdowntimer timer =NewCountdowntimer (15 * 60 * 1000, 1000) { /*** Fixed interval is called, that is, every countdowninterval will callback once method Ontick *@parammillisuntilfinished*/@Override Public voidOnTick (Longmillisuntilfinished) {Tv_remaining_time.settext (Formattime (millisuntilfinished)); } /*** Called when the countdown is complete*/@Override Public voidonfinish () {Tv_remaining_time.settext ("00:00"); } }; /*** Convert milliseconds to minutes: format of seconds * *@paramMillisecond milliseconds *@return */ PublicString Formattime (Longmillisecond) { intMinute//minutes intSecond//Number of secondsMinute = (int) ((millisecond/1000)/60); Second= (int) ((millisecond/1000)% 60); if(Minute < 10) { if(Second < 10) { return"0" + Minute + ":" + "0" +second; } Else { return"0" + Minute + ":" +second; } }Else { if(Second < 10) { returnMinute + ":" + "0" +second; } Else { returnMinute + ":" +second; } } } /*** Cancel Countdown*/ Public voidTimercancel () {timer.cancel (); } /*** Start Countdown*/ Public voidTimerstart () {Timer.start (); }
There are two parameters that need to be passed in the construction method:
Parameter 1: Total time of countdown, Unit MS
Parameter 2: Countdown time interval, Unit ms
Method:
Cancel (): Cancel Countdown
OnFinish (): Callback When the current task is completed
OnTick (Long millisunitilfinished): Callback for the current task every time the countdown interval is completed
Start (): Start countdown
Android Countdown implementation