CountDownTimer in Android using Java

Tags: , , , ,



I am trying to implement a timer in android. I am using the countdowntimer. Here, is the timer code:

 new CountDownTimer(totalTime * 1000, 1000) {
        @Override
        public void onTick(long l) {
            int newSec = (int) (sec - (sec - (l / 1000)));
            if(l % 60 == 0) {
                min--;
            }
            if(newSec < 10) {
                tv_timer.setText(min + ":" + z + newSec);
            } else {
                tv_timer.setText(min + ":" + newSec);
            }
        }

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

The timer keeps updating the amount of time left on the user’s screen.

The problem is the timer keeps ending at 00:01 (1 second), it never displays 00:00 and the alarm tone rings 2 seconds after the timer ends.

How can i get 00:00 to be displayed and how to get the alarm tone to ring immediately after the timer ends?

This is the seekbar code. The seekbar is used by the user to set the timer:

seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            z = 0;
            min = i / 60;
            sec = i - min * 60;
            if(sec < 10) {
                tv_timer.setText(min + ":" + z + sec);
            } else {
                tv_timer.setText(min + ":" + sec);

            }
            totalTime = i;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

Answer

As shown in the CountDownTimer documentation

onTick(long millisUntilFinished)

millisUntilFinished long: The amount of time until finished.

Which means that 00:00 won’t ever be shown in your code because the onTick won’t be called when there is no time left to be finished.

Simply you have to show the 00:00 inside onFinish

@Override
        public void onFinish() {
            tv_timer.setText("00:00");
            mediaPlayer.start();
        }

About the alarm tone, seems that it rings immediately after the count down is finished. You have to check that the tone itself doesn’t have a silent one or two seconds in the beginning.



Source: stackoverflow