如何将参数传递给 Workmanager DoWork 方法

How to pass parameters to Workmanager DoWork method

我想安排任务在 24 小时后从数据库中删除

public class WorkManager extends Worker {

    public WorkManager(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        return null;
    }}

我怎样才能像这样将要删除的任务作为参数传递给 DoWork 方法...

public void deleteTask(Task task){
        DataBaseHelper db = new DataBaseHelper(context);
        db.deleteOne(task);
    }

Workerclass还是不支持自定义对象作为参数传入Data。您可以做的是调整 deleteOne 方法以根据 id 删除任务,并将要删除的 id 传递给 Worker.

  public static OneTimeWorkRequest create(String id) {
      Data inputData = new Data.Builder()
              .putString(TASK_ID, id)
              .build();
      return new OneTimeWorkRequest.Builder(SampleWorker.class)
              .setInputData(inputData)
              .setInitialDelay(24, TimeUnit.HOURS)
              .build();
 }

...

@NonNull
@Override
public Result doWork() {
    String taskId = getInputData().getString(TASK_ID);

    ...
    ...
}

如果您仍然坚持将 Task 作为参数传递给您的 Worker,您可以尝试

 public static OneTimeWorkRequest create(Task task) {
     String strTask = new Gson().toJson(task);
     Data inputData = new Data.Builder()
             .putString(TASK, strTask)
             .build();
     return new OneTimeWorkRequest.Builder(SampleWorker.class)
             .setInputData(inputData)
             .setInitialDelay(24, TimeUnit.HOURS)
             .build();
 }

 ...

 @NonNull
 @Override
 public Result doWork() {
     String strTask = getInputData().getString(TASK);
     Task task = new Gson().fromJson(strTask, Task.class);

    ...
    ...
 }

build.gradle 中为 Gson 添加此依赖项

implementation 'com.google.code.gson:gson:2.8.6'

有关更多信息和研究,请查看 here