0

I saw no real answer for this type of using "handler.posDelayed".

So, I execute "handler.posDelayed" multiple times with a for-loop. The problem is, when I leave the activity and restart it, the new objects AND the old ones from the handler are executed too. I don't know, how to stop the old objects from the handler.

        private Handler handler = new Handler();

        private void startHandler() {

            handler.removeCallbacksAndMessages(runnable); // DOESN'T WORK

            long time = 0;
            for(int i = 0; i < balls.length; i++){
                handler.postDelayed(runnable, time + i);
            }
        }

        private Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // Some code..
            }
        };
Jeff
  • 27
  • 2
  • 9
  • are you calling `removeCallbacksAndMessages` in on `onPause` / `onStop` / `onDestroy` ? – pskink Jun 20 '15 at 18:47
  • Currently only in the "startHandler" method. The method is called when I start the activity, so it doesn't matter I think. I think the problem is, that the loop creates multiple runnables.@pskink – Jeff Jun 20 '15 at 18:53
  • there is only one Runnable, it is not duplicated – pskink Jun 20 '15 at 18:54
  • Okay. But I'm calling `handler.removeCallbacksAndMessages(runnable);` at the start of the activity, also if it's restarted. So why it doesn't work? – Jeff Jun 20 '15 at 18:58
  • it works, you most likely have "old" Runnables from "old" Activity that are not removed in onPause / onStop / onDestroy – pskink Jun 20 '15 at 19:00
  • btw shouldn't you call `removeCallbacks` , not `removeCallbacksAndMessages` ? – pskink Jun 20 '15 at 19:22
  • You are right with `removeCallback`. I tried `onStop` and `onDestroy` and it works now! Thank you! If you write an answer I'll mark it as correct. :) – Jeff Jun 20 '15 at 19:35
  • but removeCallbacksAndMessages in onStop or onDestroy didn't work ? – pskink Jun 20 '15 at 19:37
  • Yes, `removeCallbacksAndMessages` in onStop/onDestroy didn't work, but `removeCallbacks` in onStop/onDestroy did. – Jeff Jun 20 '15 at 19:39

1 Answers1

2

first, you should use removeCallbacks(), not removeCallbacksAndMessages()

also it seems that you have pending Runnables that you should remove when your Activity says "bye bye", so try to call removeCallbacks() in onPause / onStop / onDestroy

pskink
  • 23,874
  • 6
  • 66
  • 77