【问题标题】:code to be executed every x milliseconds, changeable每 x 毫秒执行一次的代码,可更改
【发布时间】:2019-05-06 03:50:22
【问题描述】:

我有一个代码每 x 毫秒执行一次,其中 x 在应用生命周期内是可变的。

现在我使用处理程序的 postDelayed 函数,但是当延迟发生变化时我无法管理这种情况。

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // do some staff

        handler.postDelayed(this, x);
    }
}, x);   

我的问题是在应用程序的其他部分x值可以改变,我需要在改变后立即执行run函数中的代码,并继续无限执行延迟代码(新值为x)。

【问题讨论】:

    标签: java android android-handler postdelayed


    【解决方案1】:

    保存对您的Runnable 的引用并将延迟保留为类变量,如下所示:

    private Long x = 1000L;
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            // do some staff
            handler.postDelayed(this, x);
        }
    }
    

    然后

    handler.post(r);
    

    开始吧。

    然后创建一个负责更改的setter and getter for x

    setX(Long: value){ 
        if(x != value){
            x = value
            handler.removeCallbacks(r);
            //run immediately
            handler.post(r);
        }
    }
    
    getX(){ return x };
    

    【讨论】:

    • 你能解释一下吗?我不明白我必须在我的代码中更改什么。
    • 查看编辑。诀窍是使用getters and setters
    • 谢谢。这段代码正在服务中,那么在服务中获取和设置呢?我该如何解决这个问题?
    • 如何更改x?确保x 在服务类中,然后它可以工作。
    • 您确实在问题中过度简化了您的问题,没有提到代码在服务中运行并且 x 在共享首选项中。提出的问题已解决,请停止添加新问题,而是考虑您得到的答案以及如何使用它们,如果您遇到更多问题,请重新提出新问题。
    【解决方案2】:

    如何创建具有x 作为静态变量的新类

    class DelayInterval { 
        public static int x = 1000;
    }
    

    当打电话给你的postDelay

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // do some staff
    
            handler.postDelayed(this, DelayInterval.x);
        }
    }, DelayInterval.x);   
    

    在你代码的某个地方,你可以改变 x

    DelayInterval.x = 3000;
    

    【讨论】:

    • 问题是,如果我有一个 100 秒的“x”,我在 1 秒内更改它,下一次运行可能会在 99 秒之后,而不是我需要被执行当 x 值发生变化时立即生效。
    • 那么你需要在更改 x 时取消该过程并使用新值 x 再次调用它,查看此链接 stackoverflow.com/questions/4378533/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2016-07-20
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    相关资源
    最近更新 更多