Search code examples
androidandroid-handlerandroid-runonuithread

Remove callback not working in Handler


I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?


Solution

  • The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one. There are plenty of ways to refactor this. For example:

    handler=new Handler();
    handler.post(runnable);
    public Runnable runnable = new Runnable() {
    
        @Override
        public void run() {
            boolean reschedule = myFunction(position);
            if(reschedule) {
                handler.postDelayed(runnable,10000);
            }
        }
    };
    public boolean myFunction(int position)
    {
        if(position>10) {
            return false;
        }
        return true;
    }
    

    You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.