CountDownTimer导致的内存泄露问题

项目中验证码登录有个倒计时,获取完验证码点击登录,就会引发内存泄漏,因为

CountDownTimer里面有handler,在点击登录时,倒计时还在继续,就会引发内存泄露,解决方式:
public class CountDownTimerUtils extends CountDownTimer {
    private WeakReference<TextView> mTextView;

    /**
     * @param millisInFuture    The number of millis in the future from the call
     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
     *                          is called.
     * @param countDownInterval The interval along the way to receive
     *                          {@link #onTick(long)} callbacks.
     */
    public CountDownTimerUtils(Button textView, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        this.mTextView = new WeakReference(textView);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //用弱引用 先判空,避免崩溃
        if (mTextView.get() == null) {
            cancel();
            return;
        }
        mTextView.get().setClickable(false);//不可点击
        mTextView.get().setText(millisUntilFinished / 1000 + "秒");
    }

    @Override
    public void onFinish() {
        //用软引用 判空
        if (mTextView.get() == null) {
            cancel();
            return;
        }
        mTextView.get().setText("重新获取");
        mTextView.get().setClickable(true);//不可点击

    }

    public void cancle() {
        if (this != null) {
            this.cancel();
        }
    }
}

上面是封装了一个倒计时的工具类,直接粘到项目就能使用。

之后在需要倒计时的activity或者fragment中:

在最外面先创建对象,方便页面关闭时,回收。

 CountDownTimerUtils mCountDownTimerUtils = null;

在触发倒计时的地方,加入以下代码块:

 //倒计时一分钟后可以重写获取验证码
            if (mCountDownTimerUtils == null) {
                mCountDownTimerUtils = new CountDownTimerUtils(btnLoginVerify, 60000, 1000);
            }
            mCountDownTimerUtils.start();

最后在onDestory()中加入回收代码块

@Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimerUtils != null) {
            mCountDownTimerUtils.cancel();
            mCountDownTimerUtils = null;
        }
    }

完活。

这是自己碰到的一个倒计时获取验证码的一个案例,其余的也都基本上大同小异。记录一下

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值