Android擷取驗證碼後倒計時程式

來源:互聯網
上載者:User

標籤: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 timeCountUtiltimeCountUtil = new TimeCountUtil(this, 60000, 1000, verficationBtn);
                timeCountUtil.start();

                              // 擷取驗證碼
getVerificationCode(phoneNum);

實現的


是不是很簡單,希望可以協助小夥伴們!

Android擷取驗證碼後倒計時程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.