上次写过系统提供的验证码倒计时的一个类 CountDownTimer 但是这个类在使用的时候总是会出现倒计时的偏差,所以只好自##### 己使用 Handler 或者 Timer 来实现。项目中 注册、忘记密码还##### 有现在有出现一个直接拿手机号码配合验证码直接登陆的都用到了验证码倒计时,这是后我们不可能每个类里面都使用 Handler,最直接的就是抽取出来一个,也减少了代码的重复性。
我就跟着系统的 CountDownTimer 直接仿了一个来重复使用。
示例代码
public abstract class CountDownTimer {
private static final String TAG = "CountDownTimer";
/**
* 倒计时间
*/
private int millisInFuture;
private int mCountTimer;
/**
* 倒计时间隔时间
*/
private final int mCountdownInterval;
private static final int MSG = 1;
/**
* boolean representing if the timer was cancelled
*/
private boolean mCancelled = false;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG:
synchronized (CountDownTimer.this) {
if (mCancelled) {
return;
}
if (millisInFuture <= 0) {
millisInFuture = mCountTimer;
onFinish();
} else {
onTick(millisInFuture);
millisInFuture--;
mHandler.sendEmptyMessageDelayed(MSG, mCountdownInterval);
}
}
break;
}
}
};
/**
* Cancel the countdown.
*/
public synchronized final void cancel() {
mCancelled = true;
if (mHandler.hasMessages(MSG)|mHandler!=null) {
mHandler.removeMessages(MSG);
onFinish();
}
}
public CountDownTimer(int millisInFuture, int mCountdownInterval) {
this.millisInFuture = millisInFuture;
this.mCountdownInterval = mCountdownInterval;
this.mCountTimer = millisInFuture;
}
/**
* Callback fired on regular interval.
*
* @param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
* 倒计时结束
*/
public abstract void onFinish();
/**
* Start the countdown.
*/
public synchronized final CountDownTimer start() {
mCancelled = false;
Log.e(TAG, "start: " + millisInFuture);
if (millisInFuture <= 0) {
onFinish();
return this;
}
Log.e(TAG, "start1: " + millisInFuture);
mHandler.sendEmptyMessage(MSG);
return this;
}
}
- 上面的直接复制到项目里面就可以重复使用了,代码是从项目里直接贴的这里就不上传代码和效果图了。
如果要是类名不更改记得在使用的过程中药导入自己的包名而不是系统的 的包名。