Android短信驗證碼倒計時


有兩種實現方法

1、第一種方式:Timer

/**
 * Description:自定義Timer
 * <p>
 * Created by Mjj on 2016/12/4.
 */
 
public class TimeCount extends CountDownTimer {
 
  private Button button;
 
  //參數依次為總時長,和計時的時間間隔
  public TimeCount(Button button, long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    this.button = button;
  }
 
  //計時過程顯示
  @Override
  public void onTick(long millisUntilFinished) {
    String time = "(" + millisUntilFinished / 1000 + ")秒";
    setButtonInfo(time, "#c1c1c1", false);
  }
 
  //計時完畢時觸發
  @Override
  public void onFinish() {
    setButtonInfo("重新獲取", "#f95353", true);
  }
 
  /**
   * 驗證按鈕在點擊前后相關設置
   *
   * @param content 要顯示的內容
   * @param color  顏色值
   * @param isClick 是否可點擊
   */
  private void setButtonInfo(String content, String color, boolean isClick) {
    button.setText(content);
    button.setBackgroundColor(Color.parseColor(color));
    button.setClickable(isClick);
  }
}

2、第二種方式:Handler

/**
   * 第二種方式:使用Handler
   * <p>
   * 靜態內部類:避免內存泄漏
   */
  private static class MyHandler extends Handler {
 
    private final WeakReference<MainActivity> weakReference;
 
    public MyHandler(MainActivity activity) {
      weakReference = new WeakReference<MainActivity>(activity);
    }
 
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      MainActivity activity = weakReference.get();
      if (activity != null) {
        switch (msg.what) {
          case 0:
            if (msg.arg1 == 0) {
              btn2.setText("重新獲取");
              btn2.setBackgroundColor(Color.parseColor("#f95353"));
              btn2.setClickable(true);
            } else {
              btn2.setText("(" + msg.arg1 + ")秒");
              btn2.setBackgroundColor(Color.parseColor("#c1c1c1"));
              btn2.setClickable(false);
            }
            break;
        }
      }
    }
  }
 
  /**
   * 監聽按鈕下直接調用即可
   */
  private void sendMessageClick() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        for (int i = 59; i >= 0; i--) {
          Message msg = myHandler.obtainMessage();
          msg.arg1 = i;
          myHandler.sendMessage(msg);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM