Countdown program after Android obtains the verification code
During development, you will often encounter text message Verification Code retrieval. After obtaining the verification code, you need to wait for a one-minute countdown. This means you cannot send text message requests again. This requires a countdown program.
Here I encapsulated an Util class, hoping to help developers,
Public class TimeCountUtil extends CountDownTimer {
Private Activity mActivity;
Private Button btn; // Button
// In this constructor, You need to input three parameters: Activity, millisInFuture, countDownInterval, and the button on which you perform this operation, just upload the button.
Public TimeCountUtil (Activity mActivity, long millisInFuture, long countDownInterval, Button btn ){
Super (millisInFuture, countDownInterval );
This. mActivity = mActivity;
This. btn = btn;
}
@ SuppressLint ("NewApi ")
@ Override
Public void onTick (long millisUntilFinished ){
Btn. setClickable (false); // you cannot click
Btn. setText (millisUntilFinished/1000 + "resend after seconds"); // set the countdown time
// When the set button is gray, you cannot click it.
Btn. setBackground (mActivity. getResources (). getDrawable (R. drawable. bg_duck_back ));
Spannable span = new SpannableString (btn. getText (). toString (); // get the text of the button
Span. setSpan (new ForegroundColorSpan (Color. RED), 0, 2, Spannable. SPAN_INCLUSIVE_EXCLUSIVE); // The countdown time is RED.
Btn. setText (span );
}
@ SuppressLint ("NewApi ")
@ Override
Public void onFinish (){
Btn. setText ("re-obtain Verification Code ");
Btn. setClickable (true); // obtain the Click again
Btn. setBackground (mActivity. getResources (). getDrawable (R. drawable. bg_btn_back); // restore the background color
}
}
Call Method
Then you can use this method to create an object and call start ();
CountUtil timeCountUtil = new TimeCountUtil (this, 60000,100 0, verficationBtn );
TimeCountUtil. start ();
// Obtain the verification code
GetVerificationCode (phoneNum );
Implemented
Is it very easy, hope to help friends!