Android: CountDownTimer skips last onTick()!

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

Code:

public class SMH extends Activity {  

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


        
12条回答
  •  旧时难觅i
    2020-11-27 14:56

    I've spent hours trying to figure out this problem, and I'm happy to show you a nice work around. Don't bother waiting for the onFinish() call, just add 1 (or whatever your interval is) to your units, then add an if statement in the onTick() calls. Just do your onFinish() task(s) on the last onTick(). Here's what I've got:

        new CountDownTimer( (countDownTimerValue + 1) * 1000, 1000) { //Added 1 to the countdownvalue before turning it into miliseconds by multiplying it by 1000.
            public void onTick(long millisUntilFinished) {
    
              //We know that the last onTick() happens at 2000ms remaining (skipping the last 1000ms tick for some reason, so just throw in this if statement.
                if (millisUntilFinished < 2005){ 
                    //Stuff to do when finished.
                }else{
                    mTextField.setText("Time remaining: " + (((millisUntilFinished) / 1000) - 1));  //My textfield is obviously showing the remaining time. Note how I've had to subtrack 1 in order to display the actual time remaining.
                }
            }
    
            public void onFinish() {
            //This is when the timer actually finishes (which would be about 1000ms later right? Either way, now you can just ignore this entirely.
    
    
            }
        }.start();
    

提交回复
热议问题