How to change/reset handler post delayed time?

妖精的绣舞 提交于 2019-12-18 02:43:28

问题


I'm using postDelayed method of the Handler in order to perform an action after certain amount of time:

private static int time_to_wait = 2000;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  public void run() {
    // Make Action
  }
}, time_to_wait);

now in the middle of the waiting time i want to change the value of the remaining milliseconds due to some processing results, let's say it now waited 1000 ms and i want to make it begins to count from 2000 again, So, i set the time_to_wait value to 2000 but it doesn't take that in count as it only takes the var value (2000) and just waits that time regardless changing the time_to_wait value to any other value.


回答1:


this can be achieved by easily create a runnable that will be displayed by the handler, then creating the handler as static member, finally when you want to stop it just remove the callback of your created runnable, and if you want to restart it you have to remove the callback and assign it again:

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        // your code here
    }
};

public static Handler myHandler = new Handler();
private static final int TIME_TO_WAIT = 2000;

public void start() {
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}

public void stop() {
    myHandler.removeCallbacks(myRunnable);
}

public void restart() {
    myHandler.removeCallbacks(myRunnable);
    myHandler.postDelayed(myRunnable, TIME_TO_WAIT);
}



回答2:


you can just try

handler.removeMessage(what)
handler.sendMessageDelayed(time_to_wait + INTERVER);

every time you need first remove message and then send a new message.



来源:https://stackoverflow.com/questions/22839492/how-to-change-reset-handler-post-delayed-time

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