我正在尝试使用PeriodicWorkRequest
中的WorkManager
从远程URL定期获取数据。我已经实现了逻辑,这里的问题是Worker
没有得到任何响应。但是,它似乎在首次启动时调用doWork()
,但它没有从网络调用中获取数据。我感到惊讶的是,当我使用OneTimeWorkRequest
时,我从doWork()
以及服务器中的数据中获得了成功的结果。
我可能做错了什么?
下面的代码:
worker 类(Class)
public class WorkerClass extends Worker {
private Context context;
public static final String EXTRA_WORKER_CLASS = "extra_tag";
public SpecialOffer(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
this.context = context;
}
@NonNull
@Override
public Result doWork() {
Log.d("WORKER_PERIOD", "started");
String url = "https://sampleurl/get.php";
//Volley synchronous call
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(url, future, future);
MySingleton.getInstance(context).addToRequestQueue(request);
try {
String response = future.get();
Data data = new Data.Builder()
.putString(EXTRA_SPECIAL_CARS, response)
.build();
setOutputData(data);
Log.d("WORKER_RESPONSE", response);
return Result.SUCCESS;
} catch (InterruptedException | ExecutionException e) {
return Result.FAILURE;
}
}
}
调用任务的方法
public void callTask(){
PeriodicWorkRequest periodicRequest =
new PeriodicWorkRequest.Builder(WorkerClass.class, 15, TimeUnit.MINUTES)
.setConstraints(constraints)
.addTag("SPECIAL_OFFER")
.build();
workManager.enqueueUniquePeriodicWork("SPECIAL_OFFER",
ExistingPeriodicWorkPolicy.KEEP, periodicRequest);
workManager.getWorkInfoByIdLiveData(periodicRequest.getId())
.observe(getActivity(), workInfo -> {
Log.d("WORKER_PERIOD", "observed");
// Do something with the status
if (workInfo != null && workInfo.getState().isFinished()) {
Log.d("WORKER_PERIOD", "observed");
String ava = workInfo.getOutputData().getString(SpecialOffer.EXTRA_SPECIAL_CARS);
if (ava.equals("available")) {
showSpecialOffer(true);
} else {
showSpecialOffer(true);
}
}
});
}
最佳答案
根据PeriodicWorkRequest Documentation
因此,当您在workInfo.getState().isFinished()
中执行.observe
时,它始终会返回false
因为.isFinished() method documentation说:
关于android - 定期工作请求未在工作管理器中执行doWork,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53321077/