只用于自己笔记,不做任何赚取收益,本文转自:
解决倒计时导致的内存泄漏
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(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 / 999 + "秒后可重新发送"); //设置倒计时时间
// mTextView.setBackgroundResource(R.drawable.bg_identify_code_press); //设置按钮为灰
SpannableString spannableString = new SpannableString(mTextView.get().getText().toString());
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
mTextView.get().setText(spannableString);
}
@Override
public void onFinish() {
//用软引用 先判空 避免崩溃
if (mTextView.get() == null){
cancle();
return;
}
mTextView.get().setText("重新获取验证码");
mTextView.get().setClickable(true);//重新获得点击
//mTextView.setBackgroundResource(R.drawable.bg_identify_code_normal);
}
public void cancle() {
if (this != null) {
this.cancel();
}
}
}
点击事件,点击按钮来启动倒计时
//获取验证码
get_verification_code.setOnClickListener {
mCountDownTimerUtils = CountDownTimerUtils(get_verification_code, 60000, 1000).start() as CountDownTimerUtils?
}
//写为全局变量
private var mCountDownTimerUtils: CountDownTimerUtils ?= null
销毁Activity
override fun onDestroy() {
// 写为全局变量是为了这里用
if (mCountDownTimerUtils != null) {
mCountDownTimerUtils!!.cancel()
mCountDownTimerUtils = null
}
super.onDestroy()
}