1、声明CountDownTimer的成员变量:
private CountDownTimer countDownTimer;
2、设置倒计时总时间和间隔时间:
countDownTimer = new CountDownTimer(60*1000,1000) {
@Override
public void onTick(long millisUntilFinished) { //正在计时,按钮不可点击;
bt.setText(millisUntilFinished/1000<10?"重新发送:0"+millisUntilFinished/1000+"s":"重新发送:"+millisUntilFinished/1000+"s");
bt.setEnabled(false);
}
@Override
public void onFinish() { //计时完成,按钮状态恢复可点击;
bt.setText("发送验证码");
bt.setEnabled(true);
}
};
3、点击按钮,开始计时:
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
countDownTimer.start();
}
});
4、在onDestroy()方法中注销一下;
if (countDownTimer != null){
countDownTimer.cancel();
countDownTimer = null;
}