有什么方法可以将我的 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);
}
}
});
}