Search code examples
javaandroidtimercountdowntimer

I have problem in android studio with making timer


In the app, I reopen the same activity that the timer is in. The first time timer works but after that it starts bugging the Runs onFinish() at random time. How can I fix that?

new CountDownTimer(10000, 1000) {
    public void onTick(long millisUntilFinished) {
        textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
    }
    public void onFinish() {
        wrongAnswer();
    }
}.start();

Solution

  • You must store CountDownTimer in timer and cancel it when you move to another activity or fragment ;

    Create CountDownTimer as global variable(above onCreate)

    CountDownTimer timer;
    

    Initialize timer where you want start a timer or whenever

    timer = new CountDownTimer(10000, 1000) {
    
            public void onTick(long millisUntilFinished) {
                textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
            }
    
            public void onFinish() {
                wrongAnswer();
            }
        }.start();
    

    And in onDestroy cancel it

    @Override
    protected void onDestroy() {
        if(timer != null) timer.cancel();
        super.onDestroy();
    }