Android WorkManager retrieve all requests

Viewed 729

I using WorkManager instead of AlarmManager and i want to update a request at runtime so i need to retrieve that request. How can i do that?

OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TripWorker.class)
                           .setInputData(dataBuilder.build())
                           .setInitialDelay(milliseconds, TimeUnit.MILLISECONDS)
                           .addTag("Tag")
                           .build();

workManager.enqueue(request);
3 Answers

You can use getWorkInfoByIdLiveData or getWorkInfoByTagLiveData. WorkManager adds an implicit tag to every enqueue() which is the simple name of the class. So you can do something like:

workManager.getWorkInfosByTagLiveData(TripWorker.class.getName())

You cannot modify an existing WorkRequest.

You can use WorkManager's unique work and enqueue a modified WorkRequest to replace the existing one:

  1. Use enqueueUniqueWork instead of using enqueue
  2. When you need to modify the WorkRequest, create a new one and enqueue it with UniqueWorkRequest, using the same unique name, with a REPLACE policy.

Keep in mind that the your Worker maybe running while you replace it. You need to carefully handle stoppages in your Worker (stoppages are cooperative, so you need to add some code as explained in the guide) using the isStopped method and implementing the onStopped() callback.

Unfortunately it doesn't seem to be possible as of v2.7.1 to get the WorkRequest that was submitted.


For people that want to view input data that was passed to a work request:

What you can do is to save the input data of the work request on your own, e.g. in a Room table (if you use room) or anywhere else and use the ID that is returned from WorkManager.enqueue as key.

Then, by getting the list of workInfos you can query your database table (or other storage) by their IDs.

Related