How to stop handler.postDelayed in for-loop?

1.6k views Asked by At

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..
            }
        };
1

There are 1 answers

0
pskink On BEST ANSWER

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