如何更改/重置处理程序后延迟时间? [英] How to change/reset handler post delayed time?

查看:120
本文介绍了如何更改/重置处理程序后延迟时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HandlerpostDelayed方法,以便在一定时间后执行操作:

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);

现在在等待时间的中间,由于某些处理结果,我想更改剩余毫秒的值,假设它现在等待了 1000 ms ,我想让它开始计数再次从 2000 开始,因此,我将time_to_wait值设置为2000,但是它不计入该值,因为它仅采用var值(2000),而等待该时间,无论将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.

推荐答案

这可以通过轻松创建一个将由处理程序显示的可运行对象,然后将处理程序创建为静态成员,最后在您想要停止它时来实现.删除您创建的可运行对象的回调,如果要重新启动它,则必须删除该回调并重新分配它:

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);
}

这篇关于如何更改/重置处理程序后延迟时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆