【问题标题】:How to call more than one methods at regular interval using handlers?如何使用处理程序定期调用多个方法?
【发布时间】:2023-03-06 01:09:01
【问题描述】:

我知道如何使用 handler 和 runnable 定期调用方法。但是现在我想定期调用多个方法。下面是我的一个类中的代码:

 private Handler handler = new Handler();
 private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for(int index = 0; index < count; index++) {
                    //Do something based on the index value
            }
            handler.postDelayed(runnable, 500);
        }
    };

在我的代码中的某处,我将使用以下代码开始执行:

handler.postDelayed(runnable, 0);

所以索引 0 对应的第一个方法会先被调用,然后是其他方法。然后会有 500 毫秒的延迟来重复相同的操作。

但我还希望方法调用之间有 500 毫秒的延迟。我的意思是当执行循环时。我怎样才能只使用一个处理程序并且可以运行?如何在方法调用之间产生 500 毫秒的延迟?

【问题讨论】:

    标签: android runnable android-handler


    【解决方案1】:

    我会自己在Handler 调用中更新index 的值,并将其与count 变量进行比较,就像for 循环一样

    private Handler handler = new Handler();
     private Runnable runnable = new Runnable() { 
        private int index = 0;
    
        @Override 
        public void run() { 
            //Do something based on the index value 
            index++;
            if (index < count) {
                handler.postDelayed(runnable, 500); 
            } else {
                count = 0;
            }
        } 
    }
    

    另外,一开始你不需要零延迟调用postDelayed(),你可以直接调用post()

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多