I'm trying to get data from a remote url periodically using PeriodicWorkRequest
in WorkManager
. I have implemented the logic, the issue here is that i don't get any response from the Worker
.
However it seems to call doWork()
at first launch, but it doesn't get data from the network call. I am surprised that when i use OneTimeWorkRequest
i get a success result from doWork()
and the data from server as well.
what could i be doing wrong?
code below:
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;
}
}
}
Method to call task
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);
}
}
});
}
ExistingPeriodicWorkPolicy.REPLACE
ç–略。 - Jeel Vankhedereplace
策略会替换已经存在的worker,而不是像keep
一样简单地忽略它。你可以尝试提供退避准则给你的worker
,这样如果它运行失败了,就可以在给定的准则后再次尝试。我也遇到过同样的问题,但通过提供的解决方法已经解决了。如果问题仍然存在,请告诉我。我们会为您尝试其他方法。 - Jeel Vankhede