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

时间:2018-11-15 13:57:34

标签: android android-architecture-components android-jetpack android-workmanager

我正在尝试使用PeriodicWorkRequest中的WorkManager定期从远程URL获取数据。我已经实现了逻辑,这里的问题是Worker没有得到任何响应。

但是,它似乎在第一次启动时调用了doWork(),但是它没有从网络调用中获取数据。令我惊讶的是,当我使用OneTimeWorkRequest时,我从doWork()中获得了成功的结果,并且还从服务器中获得了数据。

我做错了什么?

以下代码:

工人阶级

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);
                        }
                    }
                });
}

1 个答案:

答案 0 :(得分:0)

根据PeriodicWorkRequest Documentation

  

PeriodicWorkRequest的正常生命周期为ENQUEUED-> RUNNING-> ENQUEUED。根据定义,定期工作不能以成功或失败的状态终止,因为它必须重复进行。它只有在明确取消的情况下才能终止

因此,当您在workInfo.getState().isFinished()中进行.observe时,它总是返回false 因为.isFinished() method documentation说:

  

对于成功,失败和*取消状态返回true