Search code examples
androidandroid-workmanager

Android WorkManager retrieve all requests


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

Solution

  • 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.