How to solve multiple instance issue on a work manager?
Asked Answered
V

2

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.

Vulva answered 14/10, 2018 at 6:16 Comment(2)
Try changing your activity type to SingleInstance in your manifest.Muirhead
Share the code of your PeriodicWorkRequest class.Bacchanalia
T
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())

}
Trestle answered 3/3, 2019 at 16:9 Comment(0)
V
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

Valuator answered 23/10, 2018 at 20:17 Comment(1)
2 things: you can't schedule PeriodicWork in the beginUniqueWork method, and tags don't make a WorkRequest unique.Calbert

© 2022 - 2024 — McMap. All rights reserved.