启动
CountDownTimerUtil countDownTimerUtil = new CountDownTimerUtil (button,60000,1000);
countDownTimerUtil.start();
停止
countDownTimerUtil.onStop(countDownTimerUtil);
工具类
public class CountDownTimerUtil extends CountDownTimer {
private Button timeButton;
public CountDownTimerUtil(Button button, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.timeButton = button;
}
//停止计时器
public void onStop(CountDownTimer countDownTimer){
countDownTimer.cancel(); //终止计时器
}
//计时过程
@SuppressLint("StringFormatMatches")
@Override
public void onTick(long l) {
//防止计时过程中重复点击
timeButton.setClickable(false);
timeButton.setText(l/1000+"秒后重新发送");
}
//计时完毕的方法
@Override
public void onFinish() {
//重新给Button设置文字
timeButton.setText("重新获取");
//设置可点击
timeButton.setClickable(true);
}
}
参考:
https://codeleading.com/article/62405104830/