Android獲取驗證碼后倒計時程序
在開發是經常會遇到獲取短信驗證碼,然后獲取驗證碼后需要等待1分鐘倒計時,這是是不能再次發送短信請求的,這是需要一個倒計時程序
這里封裝了一個Util類,希望對開發的小伙伴能有幫助,
public class TimeCountUtil extends CountDownTimer {
private Activity mActivity;
private Button btn;//按鈕
// 在這個構造方法里需要傳入三個參數,一個是Activity,一個是總的時間millisInFuture,一個是countDownInterval,然后就是你在哪個按鈕上做這個是,就把這個按鈕傳過來就可以了
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);//設置不能點擊
btn.setText(millisUntilFinished / 1000 + "秒后可重新發送");//設置倒計時時間
//設置按鈕為灰色,這時是不能點擊的
btn.setBackground(mActivity.getResources().getDrawable(R.drawable.bg_duck_back));
Spannable span = new SpannableString(btn.getText().toString());//獲取按鈕的文字
span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//講倒計時時間顯示為紅色
btn.setText(span);
}
@SuppressLint("NewApi")
@Override
public void onFinish() {
btn.setText("重新獲取驗證碼");
btn.setClickable(true);//重新獲得點擊
btn.setBackground(mActivity.getResources().getDrawable(R.drawable.bg_btn_back));//還原背景色
}
}
調用方法
然后在需要用這個的方法里new一個對象,然后調用start();方法就可以啦
CountUtil timeCountUtil timeCountUtil = new TimeCountUtil(this, 60000, 1000, verficationBtn);
timeCountUtil.start();
// 獲取驗證碼
getVerificationCode(phoneNum);
實現的效果圖

來自: