Search code examples
androidandroid-workmanager

Is it okay to enqueue work with WorkManager in onCreate()?


Should WorkManager initialize once or it is okay to enqueue work in onCreate to run every time the app starts?

PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(MyWorker.class,30, TimeUnit.MINUTES).addTag("myWorkertag").build();
WorkManager workManager = WorkManager.getInstance(context);
workManager.enqueue(request);

Solution

  • Doing this will add a new work request each time your activity starts, which is probably not what you want for periodic work.

    You can use WorkManager.enqueueUniquePeriodicWork(...) which allows you to enqueue work with a unique name, where only one request with that name can be active at once. It also allows you to specify whether you want existing work to be replaced or kept via the existingPeriodicWorkPolicy parameter.