android 工作请求 运行 处于无限循环中

android WorkRequest is running in an infinte loop

我想要 运行 的任务在 doWork() 中。应用程序的这一部分在调用 scheduleUpdateJob() 时开始。它依次通过执行操作的工作请求执行 doWork()。在 doWork() 结束时,调用 updateSchedule() 将 periodicRequest 设置为每 15 分钟执行一次 doWork()。我的问题是 updateSchedule 立即调用 doWork,后者在无限循环中调用其调用函数。我是不是做错了什么。

public class EarthquakeUpdateWorker extends Worker {

    private static String PERIODIC_WORK_ID = "PERIODIC_WORK_ID";

    public EarthquakeUpdateWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    public static void scheduleUpdateJob(Context context) {
        WorkRequest workRequest = new OneTimeWorkRequest.Builder(EarthquakeUpdateWorker.class).setConstraints(Constraints.NONE).build();
        WorkManager workManager = WorkManager.getInstance();
        workManager.enqueue(workRequest);
  
    }

    @NonNull
    @Override
    public Result doWork() {
        // STUFF_TO_DO
        updateSchedule(getApplicationContext());
        return Result.success();
    }

    private static void updateSchedule(Context context) {
        Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.NOT_REQUIRED).build();
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        Boolean autoUpdate = sharedPreferences.getBoolean(PreferenceActivity.PREF_AUTO_UPDATE, true);
        int updateFreq = Integer.parseInt(sharedPreferences.getString(PreferenceActivity.PREF_UPDATE_FREQ, "60"));

        if(autoUpdate) {
            PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).build();
            WorkManager workManager = WorkManager.getInstance();
            workManager.enqueue(workRequest);
           
        }
    }

}

在创建 PeriodicWorkRequest

时设置 initial delay

替换:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).build();

:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(EarthquakeUpdateWorker.class, updateFreq, TimeUnit.MINUTES).setInitialDelay(updateFreq, TimeUnit.MINUTES).build();

不要从 doWork() 回调中调用 updateSchedule()。从一开始就将其安排为定期工作请求,而不是 one-time 运行一次后重新安排为定期工作请求。

这就是周期性工作请求的全部要点:它们稍后会自动重复,直到明确取消。