Android provides a convenient class Android.os.CountDownTimer for the verification Code countdown
How to use it:
New Countdowntimer (30000, +) { publicvoid OnTick (long millisuntilfinished) { mtextfield.settext ("seconds remaining:" + millisuntilfinished/1000); } publicvoid onfinish () { mtextfield.settext ("done!" ); } }. Start ();
OnTick Interval callback onfinish Countdown end Callback
From the source can see its implementation is mainly through the sendmessagedelayed implementation, its main logic is as follows:
PrivateHandler Mhandler =NewHandler () {@Override Public voidhandlemessage (Message msg) {synchronized(Countdowntimer. This) { if(mcancelled) {return; } Final LongMillisleft = Mstoptimeinfuture-Systemclock.elapsedrealtime (); if(Millisleft <= 0) {onfinish (); } Else if(Millisleft <mcountdowninterval) { //no tick, just delay until donesendmessagedelayed (Obtainmessage (MSG), millisleft); } Else { LongLasttickstart =Systemclock.elapsedrealtime (); OnTick (Millisleft); //Take into account user's OnTick taking time to execute LongDelay = Lasttickstart + Mcountdowninterval-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); } } } };
It is possible to do some related logic at a later time by doing some timed operations.
Android Verification Code Countdown implementation