Search code examples
androidandroid-workmanager

Android : WorkManager Update Repeat Interval Runtime


I have created WorkRequest on WorkManager. I just used first time.

I am stuck to update Repeat Interval when server sends me new interval.

Is this possible to update WorkRequest's Interval runtime when its changed on server side.

I have tried as follow:

My code is:

public static void startLocationTracker() {
        /**
         * Getting Default Minutes from General Params
         */
        List<GeneralParamMaster> generalParamMasters = CommonUses.getGeneralSettings();
        int repeatInterval = 0;
        if (generalParamMasters.size() > 0) {
            repeatInterval = TextUtils.isEmpty(generalParamMasters.get(0).getAutoLatLongTime()) ? DEFAULT_LOCATION_UPDATE_TIME : Integer.parseInt(generalParamMasters.get(0).getAutoLatLongTime());
        }
        PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, repeatInterval, TimeUnit.MINUTES)
                .addTag("Location")
                .build();

        WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);
}

My Question/Confusion is::

  • What if I call same function with as above?
  • Is there any method to update interval run time?

Your help would be appreciated.


Solution

  • This works because you're enqueueing a new WorkRequest as a Unique periodic work, replacing whatever was the previour WorkRequest and its Interval.

    Keep in mind that it may happens that you replace a PeriodWorker while it is running, because you're using ExistingPeriodicWorkPolicy.REPLACE. If another worker, associated to the same UniqueName, it's running while you call enqueueUniquePeriodicWork, the Worker will be cancelled and the new one will be scheduled.

    For this reason it's important to handle the cancellation correctly in your Worker class, as explained in the documentation.