1

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);
petey
  • 16,914
  • 6
  • 65
  • 97
FreeLine
  • 71
  • 1
  • 10

1 Answers1

1

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);
petey
  • 16,914
  • 6
  • 65
  • 97
  • so the same way: dont removeCallbacksAndMessages if you dont want to run again - you dont have any "pending" `Runnable` so there is nothing to remove – pskink Jan 30 '17 at 19:41
  • yea. I'm going to assume @Freeline has other runnables looping that also need stopping so I left the `removeCallbacksAndMessages` method as is in order for that to still occur. – petey Jan 30 '17 at 19:47
  • Thanks for a quick answer. So postdelayed is what makes it run again. Didn't know that, just googled how to do something every x seconds and this is what came up. I don't have any other runnables running than that one, so I can remove "removeCallbacksAndMessages"? Will try this next time I get the chance and mark it as correct if it works. Assuming it will though. Thanks again. – FreeLine Jan 30 '17 at 20:38
  • @FreeLine great, glad my answer helped you. Can you can accept it as "the" answer to your question? – petey Jan 30 '17 at 21:02
  • @petey I will mark it as correct if it works, haven't got the chance to try it yet. – FreeLine Jan 31 '17 at 06:55