Search code examples
javaandroidrunnableandroid-handlerpostdelayed

Handler#removeCallbacksAndMessages not working properly


I created an h.postdelayed and I want to cancel that if a condition is true. I wrote the if condition and inside it I did h.removeCallbacksAndMessages(null). However, I can see the "timer" still running. Any help?

h.postDelayed(new Runnable() {
  public void run() {
    timePassed++;
    timeLeft = (maxTime - timePassed) / 10;
    timeLeftStr = "Time left: " + timeLeft + " seconds";
    timer.setText(timeLeftStr);

    if (timeLeft <= 0) {
      started = false;

      h.removeCallbacksAndMessages(null);

      setupGameOver(restartBtn, header1, header2, timer);
    }

    h.postDelayed(this, 100);
  }
}, 100);

Solution

  • Dont postDelayed if you dont want to run again

    h.postDelayed(new Runnable() {
        public void run() {
            timePassed++;
            timeLeft = (maxTime - timePassed) / 10;
            timeLeftStr = "Time left: " + timeLeft + " seconds";
            timer.setText(timeLeftStr);
    
            if (timeLeft <= 0) {
                started = false;
    
                h.removeCallbacksAndMessages(null);
    
                setupGameOver(restartBtn, header1, header2, timer);
            } else {
                // run again.
                h.postDelayed(this, 100);
            }
    
        }
    }, 100);