Android实现验证码倒计时控件
2018-03-20 本文已影响0人
handler棒棒哒
CountDownTimer原理分析
实现倒计时相关计时功能Android官方API中给出了CountDownTimer这个类专门用于实现倒计时功能的。其简单的使用如
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
该计时器采用毫秒的方式计算,最基本的原理还是采用的是Android的老熟人Handler实现异步通信更新控件的。不多说贴出源码看看:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
long delay;
if (millisLeft < mCountdownInterval) {
// just delay until done
delay = millisLeft - lastTickDuration;
// special case: user's onTick took more than interval to
// complete, trigger onFinish without delay
if (delay < 0) delay = 0;
} else {
delay = mCountdownInterval - lastTickDuration;
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
}
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
从源码看出在异步通信循环中实现了几个关键方法,也就是我们自定义倒计时控件所必须的和注意的地方
自定义倒计时控件
要自定义验证码倒计时控件我们就需要继承与CountDownTimer类并实现相应的方法。闲话不多说上代码
public class CodeCount extends CountDownTimer {
private Button button;
/**
* @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 CodeCount(Button btn, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.button = btn;
}
@Override
public void onTick(long millisUntilFinished) {
//防止计时过程中重复点击
button.setClickable(false);
button.setText("" + millisUntilFinished / 1000 + "s");
button.setBackgroundResource(R.drawable.valid_code_bg);
button.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.colorWhite));
}
@Override
public void onFinish() {
//重新给Button设置文字
button.setText("重新获取验证码");
//设置可点击
button.setClickable(true);
button.setBackgroundResource(R.drawable.code_btn_bg);
button.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.colorAccent));
}
以上就是自定义的倒计时控件啦,在需要倒计时功能的地方直接使用就行啦,不过从Android源码中我们会发现采用Handler进行异步通信易发生内存泄漏问题,不过官方也给出了相应的回收方法cancel()啦,只需要在使用时注意下就行~~
自定义控件的简单使用
CodeCount count = new CodeCount(btnCode, 60000, 1000);
count.start();
为防止内存泄漏问题在页面回收时调用对应的回收方法
@Override
protected void onDestroy() {
super.onDestroy();
if (count != null) {
count.cancel();
}
}
关于倒计时控件的简单实现和注意就分享到这里啦,本人一个入坑的小白,欢迎砖家门吐槽和鼓励,同时也希望能够给你带来一点点小帮助~~~3Q