CountDownTimer工具类

对之前写的工具类做了修改,降低耦合,方便下次直接复制粘贴

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;
}

仅此记录,希望对看到的朋友有帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值