对之前写的工具类做了修改,降低耦合,方便下次直接复制粘贴
SendSmsTimerUtils 工具类
public class SendSmsTimerUtils extends CountDownTimer {
private int countTemp = 2;
public SendSmsTimerUtils(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval / 2);
}
@Override
public void onTick(long millisUntilFinished) {
if (countTemp == 2) {
if (onCountDownListener != null) {
onCountDownListener.onTick(Math.round(millisUntilFinished / 1000.0));
}
countTemp--;
} else {
countTemp++;
}
}
private OnCountDownListener onCountDownListener;
public void setOnCountDownListener(OnCountDownListener onCountDownListener) {
this.onCountDownListener = onCountDownListener;
}
public interface OnCountDownListener {
void onTick(long tick);
void onFinish();
}
@Override
public void onFinish() {
countTemp = 2;
if (onCountDownListener != null) {
onCountDownListener.onFinish();
}
}
}
初始化及回调处理
SendSmsTimerUtils countDownTimer = new SendSmsTimerUtils(60000, 1000);
countDownTimer.setOnCountDownListener(new SendSmsTimerUtils.OnCountDownListener() {
@Override
public void onTick(long tick) {
btnGetCode.setText(String.format("%ds", tick));
}
@Override
public void onFinish() {
btnGetCode.setText("重新发送");
btnGetCode.setClickable(true);
btnGetCode.setBackground(ContextCompat.getDrawable(LoginActivity.this, R.drawable.shape_verification_code));
}
});
启动
countDownTimer.start();
btnGetCode.setClickable(false);
btnGetCode.setBackground(ContextCompat.getDrawable(LoginActivity.this, R.drawable.shape_verification_code_disable));
退出界面时候取消倒计时,防止内存泄漏
@Override
protected void onDestroy() {
super.onDestroy();
countDownTimer.cancel();
countDownTimer = null;
}
仅此记录,希望对看到的朋友有帮助