Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 短信驗證碼倒計時的簡潔實作範例

編輯:關於 Android 程式設計

前言

現在許多 App 都採用手機註冊,為了確認是本人手機,通常都會加入短信驗證碼環節。最近公司專案就用到了短信驗證碼,並要求加上倒計時功能,也就是 60 秒內只能發送一次。做個記錄,日後需要時就能隨時取用。

實作

發送驗證碼通常會有一顆按鈕,點擊後便會向輸入的手機號發送驗證碼。這裡我用一個 TextView 來顯示特定數字,只要設定它的點擊事件即可。

Android 中有一個 CountDownTimer 類別可以實現這個功能,很方便,但它有個小缺點:在最後一秒會等待較久才顯示出「重新發送」的文字。後來我發現另開一條執行緒來實作更為理想。

程式碼如下

 /** * 短信驗證碼倒計時 */ private void startTimer() { registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_color_code_green)); registerVerificationCodeTv.setText(getResources().getString(R.string.timer_default_show)); registerVerificationCodeTv.setEnabled(false); new Thread() { @Override public void run() { for (int i = 59; i >= 0; i--) { final int second = i; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { if (second <= 0) { registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_get_verification_code)); registerVerificationCodeTv.setText(getResources().getString(R.string.register_re_get_verification_code)); registerVerificationCodeTv.setEnabled(true); } else { registerVerificationCodeTv.setTextColor(getResources().getColor(R.color.text_color_code_green)); registerVerificationCodeTv.setText(second + "s"); } } }); } } }.start(); }

說明

其中 registerVerificationCodeTv 就是顯示倒計時秒數的 TextView,使用時只要在它的點擊事件中呼叫這個方法即可。透過 runOnUiThread 回到主執行緒更新介面,就能避免子執行緒操作 UI 的問題。

以上就是這個短信驗證碼倒計時的完整實作,希望對大家的開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved