Search code examples
androidandroid-handler

Handler not stopping - Android


I created one handler to repeat a task repeatedly and I also want to destroy it within that handler once a condition has been met.

pinHandler = new Handler();

Now I created two functions separately to start and stop the task.

void startRepeatingPins() {
        mPinSetter.run();
    }
    Runnable mPinSetter = new Runnable() {
        @Override
        public void run() {
            try{
                System.out.println("PinIndwx count is :"+pinIndexCount);
                if(pinIndexCount==(plist.size()-1))
                {
                    stopUpdatingPins();
                    pinIndexCount=0;
                    //pinHandler.removeCallbacks(mPinSetter);
                    System.out.println("Handler stopped by itself.");
                }
                else
                {
                    updatePoint(plist.get(pinIndexCount));
                    pinIndexCount++;
                }

            }
            finally {
                pinHandler.postDelayed(mPinSetter, pinInterval);
            }
        }
    };

    private void stopUpdatingPins()
    {
        pinIndexCount=0;
        pinHandler.removeCallbacks(mPinSetter);
        System.out.println("Called the stop function.");
    }

Now, the issue is that, if I call the stopUpdatingPins function , the handler stops but when I try to stop it automatically from within the handler, it just doesn't stop. Although the stopUpdatingPins function does get called.


Solution

  • Change You startRepeatingPins() like this, You should not directly call the run. If your run like this then there is no point of removing this from Handler. So attach Runnable with Handler.

    void startRepeatingPins() {
       pinHandler.post(mPinSetter);
    }
    

    You added post delay in finally that means you are stopping at first if loop and starting again in finally, So it's never stopping. So Change your runnable like this,

    Runnable mPinSetter = new Runnable() {
            @Override
            public void run() {
    
                    System.out.println("PinIndwx count is :"+pinIndexCount);
                    if(pinIndexCount==(plist.size()-1))
                    {
                        stopUpdatingPins();
                        pinIndexCount=0;
                        //pinHandler.removeCallbacks(mPinSetter);
                        System.out.println("Handler stopped by itself.");
                    }
                    else
                    {
                        updatePoint(plist.get(pinIndexCount));
                        pinIndexCount++;
                        pinHandler.postDelayed(mPinSetter, pinInterval);
                    }
    
    
            }
        };