如何在 java 中为 Android WorkManager 创建具有重试逻辑的 PeriodicWorkRequest?

How to create a PeriodicWorkRequest with retry logic in java for Android WorkManager?

有什么方法可以将 workInfo.getRunAttemptCount() 从我的 MainActivity 传递给 Class 扩展 Worker? 因此,我可以跟踪重试计数并重复 3 次迭代,如果请求不成功,则在 3 次重试后在 doWork() 中调用 RESULT.failure() 状态。

代码:

    public Result doWork() {

        Integer retryAttemptCount = getInputData().getInt("retryAttempts",0);

        Log.e(TAG, "doWork: Work is done." + System.currentTimeMillis());


        if (retryAttemptCount > 3)
            return Result.failure();
        else
            return Result.retry();
    }

主要活动

 private void setPeriodicWorkRequest(){

        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        // Exponential retry with a min of 15 minutes during retry.
        PeriodicWorkRequest periodicWork = new
                PeriodicWorkRequest.Builder(MyPeriodicWork.class, 15, TimeUnit.MINUTES)
                .addTag("periodic_work")
                .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                .setConstraints(constraints)
                .build();
        WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork("periodic_work", ExistingPeriodicWorkPolicy.KEEP, periodicWork);

        WorkManager.getInstance(getApplicationContext()).getWorkInfoByIdLiveData(periodicWork.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(@Nullable WorkInfo workInfo) {
                        Data.Builder data = new Data.Builder();

                        if (workInfo != null && workInfo.getRunAttemptCount() > 0) {
                            // Passing params
                            data.putInt("retryAttempts", workInfo.getRunAttemptCount());

                        }else{
                            data.putInt("retryAttempts", 0);
                        }
                    }
                });
}

你可以直接在你的Worker中调用getRunAttemptCount(); class;这是ListenableWorker的方法之一:

public class UploadWorker extends Worker {

    public UploadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
      // Do the work here--in this case, upload the images.
      Integer retryAttemptCount = getRunAttemptCount();

      try {

        uploadImages()
        return Result.success();

      } catch (Exception exception) {
        if (retryAttemptCount >= 3)
            return Result.failure();
        else
            return Result.retry();
        }
    }
}