项目中验证码登录有个倒计时,获取完验证码点击登录,就会引发内存泄漏,因为
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;
}
}
完活。
这是自己碰到的一个倒计时获取验证码的一个案例,其余的也都基本上大同小异。记录一下