android-workmanager - 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);
}
}
});
}
解决方案
您可以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();
}
}
}
推荐阅读
- php - Alexa SMAPI - 更新意图返回错误:“指定的技能或区域设置没有关联的模型。”
- angularjs - 我们可以在单击饼图图例标签时删除条形图线吗?
- html - 为什么我的 .png 网站徽标文件不会显示在我的网站上?
- php - 如何在字符串中添加新行?
- spring - Spring Security:会话有效时禁用登录页面
- linux - 为什么子进程会调用 getppid()?Parent 的 PID 可以用来做什么?
- javascript - 如何从 HTML 字符串生成动态 HTML?
- java - 如何在 jtextfield 上迭代和打印矩阵?
- flutter-layout - 如何对齐行首的第一项和行尾的第二项?
- java - 类型不匹配:无法使用 java 在 selenium webdriver 中从 ChromeDriver 转换为 WebDriver