Android: CountDownTimer skips last onTick()!

前端 未结 12 696
眼角桃花
眼角桃花 2020-11-27 14:51

Code:

public class SMH extends Activity {  

    public void onCreate(Bundle b) {  
        super.onCreate(b);  
        setContentView(R.layou         


        
12条回答
  •  星月不相逢
    2020-11-27 15:01

    I checked the source code of CountDownTimer. The "missing tick" comes from a special feature of CountDownTimer that I have not yet seen being documented elsewhere:

    At the start of every tick, before onTick() is called, the remaining time until the end of the countdown is calculated. If this time is smaller than the countdown time interval, onTick is not called anymore. Instead only the next tick (where the onFinish() method will be called) is scheduled.

    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)

        myCountDownTimer = new CountDownTimer(countDownTime, intervalTime - 500) {
                                       ...
        }
    

    and I could leave my code just as it is. For applications where the length of the interval time is critical, the other solutions posted here are probably the best.

提交回复
热议问题