安排函数甚至在循环函数上也要执行的操作

时间:2019-11-08 17:34:06

标签: android-studio

嘿,我想到的是每1分钟触发一次函数的代码,但是在循环函数中,每次执行此操作时,它都会调度函数运行55555次,没有一次停止并同时执行所有这些操作

我想做的是使其每1分钟执行一次,即使在onGpsStatusChanged或位置侦听器这样的循环函数上

Android Studio ...

3 个答案:

答案 0 :(得分:0)

  1. 您可以将Android JobScheduler用于此目的。此实现将帮助您在特定时间发布操作(包括超时)。阅读more from the documentation

  1. 另一种可能是发布此内容的简单方法,它使用的是Android Handler和发布延迟功能。对于前。

    private static final long DELAY = TimeUnit.MINUTES.toMillis(1)
    
    private void startTask() {
       new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    
          @Override
          public void run() {
              /**
               * Your function here, and start task again!
               */
               startTask()
           }
    
       }, DELAY);
    }
    

答案 1 :(得分:0)

我不确定100%的意思,因此您可以发布代码吗?无论如何,我使用它每分钟运行timerTick ...

        final Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {
                timerTick();
                handler.postDelayed(this, 1000 * 60);
            }
        };
        this.runOnUiThread(r);

答案 2 :(得分:0)

  

每1分钟触发一次函数,但每次循环函数   我这样做是为了安排功能运行55555次,没有停止,然后执行   他们在同一时间所有他们

我还将在 Android Studio上使用 JobScheduler TimerTick

final val TIME_PERIOD = TimeUnit.Milliseconds(60000)

try {
   scheduleMethod() {
     Handler(Looper.getMainLooper()).postDelayed(
       Runnable {
         execute()
       }, TIME_PERIOD)
    }
} catch (InterruptedException e) {
    e.printStackTrace();
}