解决安卓倒计时 CountDownTimer类 内存泄漏

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:43   1893   0
写如下:

public class CountDownTimerUtils extends CountDownTimer {

     WeakReference<TextView> mTextView; //显示倒计时的文字  用弱引用 防止内存泄漏
    
    public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        this.mTextView = new WeakReference(textView);
    }

    @Override
    public void onTick(long millisUntilFinished) {
        //用弱引用 先判空 避免崩溃
        if (mTextView.get() == null) {
            cancle();
            return;
        }
        mTextView.get().setClickable(false); //设置不可点击
        mTextView.get().setText(millisUntilFinished / 1000 + "秒后重新发送"); //设置倒计时时间
//        mTextView.setBackgroundResource(R.drawable.validate_code_press_bg); //设置按钮为灰色,这时是不能点击的
//        SpannableString spannableString = new SpannableString(mTextView.getText().toString()); //获取按钮上的文字
//        @SuppressLint("ResourceAsColor") ForegroundColorSpan span = new ForegroundColorSpan(R.color.text_gray);
//        /**
//         * public void setSpan(Object what, int start, int end, int flags) {
//         * 主要是start跟end,start是起始位置,无论中英文,都算一个。
//         * 从0开始计算起。end是结束位置,所以处理的文字,包含开始位置,但不包含结束位置。
//         */
//        spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色
//        mTextView.get().setText(spannableString);
        mTextView.get().setText(mTextView.get().getText().toString());
    }
    @Override
    public void onFinish() {
        //用软引用 先判空 避免崩溃
        if (mTextView.get() == null){
            cancle();
            return;
        }
        mTextView.get().setText("重新获取验证码");
        mTextView.get().setClickable(true);//重新获得点击
//      mTextView.setBackgroundResource(R.drawable.validate_code_normal_bg); //还原背景色
    }
    public void cancle() {
        if (this != null) {
            this.cancel();
        }
    }
}

使用:

private CountDownTimerUtils mCountDownTimerUtils = null; //写为全局变量
mCountDownTimerUtils = new CountDownTimerUtils(tvCountdown, 60000, 1000); //倒计时1分钟
mCountDownTimerUtils.start()
@Override
protected void onDestroy() {
    // 写为全局变量是为了这里用
    if (mCountDownTimerUtils != null) {
        mCountDownTimerUtils.cancel();
        mCountDownTimerUtils = null;
    }
    super.onDestroy();
}
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP