这里给大家介绍一种android中倒计时方法, 通过一个简单的例子来使用CountDownTimer实现倒计时10秒:
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
LogUtil.i(TAG, "seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
LogUtil.i(TAG, "done!");
}
}.start();
结果.png
可以看出CountDownTimer每隔1秒调用一次onTick(long millisUntilFinished)
方法, 倒计时结束时调用onFinish()
方法.
温馨提示:回调方法中可以直接更新UI哦~
那么我们来简单的了解一下这个类:
构造函数
CountDownTimer (long millisInFuture, long countDownInterval)
- 参数1: 你要倒计时的总时间, 单位ms.
- 参数2: 你要倒计时的间隔时间, 单位ms.
方法
public final void cancel ()
public abstract void onFinish ()
public abstract void onTick (long millisUntilFinished)
public final CountDownTimer start ()
- 方法1
cancel()
: 取消当前的任务 - 方法2
onFinish()
: 当前任务完成的时候回调 - 方法3
onTick(long millisUntilFinished)
: 当前任务每完成一次倒计时间隔时间时回调 - 方法4
start()
: 开始当前的任务
好啦~~ 对CountDownTimer的概念大家也了解的差不多了, 希望对大家的学习有所帮助~~~
最后, 提醒大家,千万别看完就忘了哦, 要学以致用!
网友评论
How did yout print the log?
D/BDNPreRollADItem__: tick-----------7
D/BDNPreRollADItem__: tick-----------6
D/BDNPreRollADItem__: tick-----------5
D/BDNPreRollADItem__: tick-----------4
D/BDNPreRollADItem__: tick-----------3
D/BDNPreRollADItem__: tick-----------2
D/BDNPreRollADItem__: tick-----------1
D/BDNPreRollADItem__: onFinish-----------
Given the fact that hardware clocks are not always super precise, that there may be other processes in the background that delay the thread running CountDownTimer plus that Android itself will probably create a small delay when calling the message handler of CountDownTimer it is more than likely that the call for the last tick before the end of the count down will be at least one millisecond late and therefore onTick() will not be called.
For my application I solved this problem simply by making the tick intervals "slightly" smaller (500 ms)'
So meybe android fixed it or a smaller delay in LZ's machine.