Search code examples
androidhandler

Remove callback for handler not work


I have written a handler that calls the method every time interval. I want to remove that handler in on destroy(). The code i use as follows, In Oncreate()

private final Handler _handler = new Handler();
public int DATA_INTERVAL = 30 * 1000;
Runnable getData;
 getData = new Runnable()
        {
            @Override
            public void run()
            {
                     recieveData();
            }
        };

 _handler.postDelayed(getData, DATA_INTERVAL);

and in ondestroy(), i use,

_handler.removeCallbacks(getData);

But removecallbacks not work. It calls after exiting the activity.


Solution

  • removeCallbacks(Runnable r):

    Remove any pending posts of Runnable r that are in the message queue.

    so removeCallbacks(..) only stops pending messages (Runnables) not currently running runnable so if you want to stop currently running Runable then use a Boolean varaible for Stoping Thread when user Exit from your app.

    see this post for removeCallbacks not stopping runnable