2

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.

Shalini
  • 1,733
  • 4
  • 17
  • 31
  • 1
    You could call `_handler.removeCallbacksAndMessages()` without any parameter. It removes everything in the callbacks and messages stack – Sergi Juanola Aug 16 '12 at 06:50
  • 1
    @Kor it gives error when calling _handler.removeCallbacksAndMessages() without parameter. – Shalini Aug 16 '12 at 07:07
  • _handler.removeCallbacksAndMessages(null) use this line and let me know if it works. – Randroid Aug 16 '12 at 08:35
  • check this link http://stackoverflow.com/questions/5883635/how-to-remove-all-callback-from-a-handler – Randroid Aug 16 '12 at 09:41
  • @Raghav thanks. but its works now by using this link http://stackoverflow.com/questions/5844308/removecallbacks-not-stopping-runnable – Shalini Aug 16 '12 at 10:08

3 Answers3

10

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

Community
  • 1
  • 1
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 5
    Wrong. Notice he's calling `removeCallbacks` from `onDestroy` which runs in the main thread. So either a pending Runnable runs first and then `onDestroy` cancels all future callbacks, or `onDestroy` runs first and cancels all future callbacks so no Runnable would run after that. He has a different problem. – Mister Smith Mar 15 '16 at 16:22
0

You are not showing the most important part of the code which is the receiveData method. As you said you are running the task periodically, you must be calling again postDelayed from inside that method to reschedule the task. Probably background threads involved as you cannot do networking on the main thread.

You most likely have a race condition when exiting the Activity. onDestroy runs first and then the task is posted again.

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
0

You should use

handler.removeCallbacksAndMessages(null);

Then all handler callbacks will removed.

Mimo Saha
  • 61
  • 4