首页 > 解决方案 > java - 如何在Java中为Android WorkManager创建带有重试逻辑的PeriodicWorkRequest?

问题描述

有什么方法可以将我的 MainActivity 中的 workInfo.getRunAttemptCount() 传递给扩展 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);
                        }
                    }
                });
}

标签: android-workmanagerretry-logic

解决方案


您可以getRunAttemptCount()直接在您的 Worker 类中调用;这是一个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();
        }
    }
}

推荐阅读