gpt4 book ai didi

android - 定期工作请求未在工作管理器中执行 doWork

转载 作者:太空狗 更新时间:2023-10-29 13:46:28 24 4
gpt4 key购买 nike

我正在尝试使用 WorkManager 中的 PeriodicWorkRequest 定期从远程 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

The normal lifecycle of a PeriodicWorkRequest is ENQUEUED -> RUNNING -> ENQUEUED. By definition, periodic work cannot terminate in a succeeded or failed state, since it must recur. It can only terminate if explicitly cancelled

所以当你在 .observe 中执行 workInfo.getState().isFinished() 时,它总是返回 false因为.isFinished() method documentation说:

returns true for SUCCEEDED, FAILED, and * CANCELLED states

关于android - 定期工作请求未在工作管理器中执行 doWork,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53321077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com