7

I have an worker to do a periodical task. and this worker is called in an activity on create. Every time the activity open there is a new instance created and do the same task in same time in multiple times. I called the task like this

task = new PeriodicWorkRequest.Builder(BackgroundTask.class, 1000000, TimeUnit.MILLISECONDS).build();
WorkManager.getInstance().enqueue(task);

how to avoid creating multiple instance? if there is no worker running i need to call the instance on create of the activity.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Arafat
  • 121
  • 1
  • 7

2 Answers2

13

You can use the fun WorkManager.enqueueUniquePeriodicWork

This function needs 3 params:

  1. tag (string) so it would look for other previously created work requests with this tag
  2. strategy to use when finding other previously created work requests. You can either replace the previous work or keep it
  3. your new work request

For example in a kotlin project where I needed a location-capturing work to run every some time, I have created a fun that started the work like this:

fun init(force: Boolean = false) {

    //START THE WORKER
    WorkManager.getInstance()
            .enqueueUniquePeriodicWork(
                    "locations",
                    if (force) ExistingPeriodicWorkPolicy.REPLACE else ExistingPeriodicWorkPolicy.KEEP,
                    PeriodicWorkRequest.Builder(
                            LocationsWorker::class.java,
                            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
                            TimeUnit.MILLISECONDS)
                            .build())

}
Re'em
  • 1,869
  • 1
  • 22
  • 28
0

You can add tag to your WorkRequest (make it unique), and then check it's status by tag, and cancel when needed. Or you can use getId() method, because it's autogenerated and cancel using this id.But this way you should save this id by yourself.

Or, for example, you can use beginUniqueWork(...) method

https://developer.android.com/reference/androidx/work/WorkManager

  • 2 things: you can't schedule `PeriodicWork` in the `beginUniqueWork` method, and tags don't make a `WorkRequest` unique. – Dean Oct 28 '18 at 17:24