Remove callback for handler not work

ⅰ亾dé卋堺 提交于 2019-12-08 09:27:05

问题


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.


回答1:


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




回答2:


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.




回答3:


You should use

handler.removeCallbacksAndMessages(null);

Then all handler callbacks will removed.



来源:https://stackoverflow.com/questions/11981899/remove-callback-for-handler-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!