引言
目前,处于安全的考虑,大部分软件账户注册都需要短信验证码,而点击验证码之后倒计时获取变得习以为常,下面个人总结了三种实现倒计时的方法。供大家参考:
1 . 谷歌原生的计时器(CountDownTimer类)
首先,由于谷歌的开发者官网对国内开放了,所以我们先去看一下关于CountDownTimer的解释和应用:
Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
//案例
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
The calls to onTick(long) are synchronized to this object so that one call to onTick(long) won't ever occur before the previous callback is complete. This is only relevant when the implementation of onTick(long) takes an amount of time to execute that is significant compared to the countdown interval.
然而对于我这种四级没过的人来说理解是:同过设置构造函数中的两个参数,第一个是倒计时需要的时间,第二个是时间的间隔,在该函数中含有两个回调函数onTick(long)
和onFinish()
,第一个回到函数回传过来剩余的时间,第二个是倒计时完成时回调的方法。下面我把我写的代码贴出来(这里我写的倒计时是六秒钟):
countDownTimer = new CountDownTimer(6000, 1000) {
int n = 6;
@Override
public void onTick(long l) {
Log.e(TAG, "onTick: " + l);
tv_time.setClickable(false);
tv_time.setText(