机器人 Calendar.MINUTE 没有 return 正确的分钟

Androids Calendar.MINUTE does not return the correct Minute

所以我有一个循环,我想每 5 分钟轮询一次数据,以将我的 api 请求保持在最低限度。问题是 CurrentMin 不会在 android phone 上的分钟更新时更新。它开始正确,但随后无法保持最新​​状态。知道如何每 5 分钟生成一次此民意调查数据吗?

while (x==false) {
    currentMin= c.get(Calendar.MINUTE); //get the current min
    System.out.println(currentMin);

    if (currentMin%5==0) {//poll the data every 5 min
        ***Poll data***
    }
}

来自How to run a method every X seconds

使用 Handler。从不,我的意思是 从不 在 Android 中使用 while 安排任务。您的电池将在几分钟内耗尽,您将锁定 UI 并使您的应用程序变慢。

Handler h = new Handler();
int delay = 1000; //interval in milliseconds

h.postDelayed(new Runnable(){
    public void run(){
        //pool data
        h.postDelayed(this, delay);
    }
}, delay);

您可以尝试使用 TimerTask。循环方法是一个非常糟糕的选择。

下面是它的用法示例

http://examples.javacodegeeks.com/android/core/activity/android-timertask-example/

使用ScheduledThreadPoolExecutor如下:

private ScheduledThreadPoolExecutor mScheduleTaskExecutor = new ScheduledThreadPoolExecutor(1);
mScheduleTaskExecutor.scheduleAtFixedRate(yourRequestRunnable, 0, 5, TimeUnit.SECONDS);

而 yourRequestRunnable 将类似于:

Runnable yourRequestRunnable = new Runnable() {
    // Do your request here
}

这将基本上保证您将以固定速率执行代码。如果您需要在请求完成后在 UI 中执行某些操作,只需将处理 UI 更改的代码包装在 runOnUiThread()