0

I want to build a 5 second timer that counts down to 0 in 1 second intervils and then resets to the initial value of 5 seconds. The timer needs to run continously. After looking at this thread, Android - loop part of the code every 5 seconds

I used the CountDownTimer Class and called the start() method within the onFinish() method so that when the timer finished, it would reset to 5. It does run on a continous loop, however I notice that after the first loop, it either countsdown as 4-3-2-1-0 or 5-3-2-1-0. Can somebody explain to me why this happens?

private long START_TIME_IN_MILLIS = 5000;
//set up our variables
private CountDownTimer timer;
private TextView textView;
private Button starttimer;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.text_view_countdown);
    starttimer = findViewById(R.id.button_start_pause);
    //set onclik listener when touch imput button
    starttimer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            beginTime();
        }
    });
}

//creating my own method
private void beginTime() {

    timer = new CountDownTimer(mTimeLeftInMillis, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeftInMillis = millisUntilFinished;
            updateCountDownText();
        }

        @Override
        public void onFinish() {
            start();
        }

    }.start();
}

private void updateCountDownText(){
    int minutes= (int) (mTimeLeftInMillis / 1000)/ 60;
    int seconds= (int) (mTimeLeftInMillis / 1000) % 60;

    String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds);
    textView.setText(timeLeftFormatted);
}

}

picciano
  • 22,341
  • 9
  • 69
  • 82
Sam Davis
  • 29
  • 5

1 Answers1

0

Try this

 @Override
        public void onFinish() {
          mTimeLeftInMillis = START_TIME_IN_MILLIS;
   }
Deepak kaku
  • 1,218
  • 9
  • 15
  • The code above didn't change anything. I tried the code below and it displayed the initail value of 5 for a fraction of a second before counting down from 4 @Override public void onFinish() { mTimeLeftInMillis = START_TIME_IN_MILLIS; updateCountDownText(); start(); } – Sam Davis Apr 12 '18 at 22:44
  • oh! can you try adding a delay? for Countdown to begin? – Deepak kaku Apr 12 '18 at 23:24