简体   繁体   中英

How to pass parameters to Workmanager DoWork method

I want to Schedule task to be deleted from the database after 24 hours

public class WorkManager extends Worker {

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

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

how can i pass the Task to be deleted as a parameter to the DoWork method like so...

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

Worker class still does not support custom object as parameters to pass in Data . What you can do is tweak your deleteOne method to delete task based on id and pass this id to be deleted to 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);

    ...
    ...
}

If you still insist on passing Task as parameter to your Worker you can try

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

    ...
    ...
 }

Add this dependency in build.gradle for Gson

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

For more information and studies check out here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM