androidandroid-workmanagerperiodic-task

Android WorkManager Periodic task not triggered when app is killed


My goal is to update my app token(using network request) in every 12 hours whether app is in background or killed so I've used workmanager to solve this. But Periodic task only work when app is in background or open but when I killed the app then periodic task stop to update my app token.

Here is my code:

WorkManager mWorkManager;
                    mWorkManager = WorkManager.getInstance(context);
                    
                    Constraints constraints = new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build();


                    PeriodicWorkRequest periodicSyncDataWork =
                            new PeriodicWorkRequest.Builder(AccessTokenUpdateWorker.class, 12, TimeUnit.HOURS)
                                    .addTag("ACCESS_TOKEN_SYNC_DATA")
                                    .setConstraints(constraints)
                                    .setInitialDelay(5, TimeUnit.MINUTES)
                                    // setting a backoff on case the work needs to retry
                                    .setBackoffCriteria(BackoffPolicy.LINEAR, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                                    .build();
                    mWorkManager.enqueueUniquePeriodicWork(
                            "ACCESS_TOKEN_SYNC_DATA",
                            ExistingPeriodicWorkPolicy.KEEP, //Existing Periodic Work policy
                            periodicSyncDataWork //work request
                    );

I'm using workmanager 2.4.0 version


Solution

  • Actually my WorkManager settings was correct but Worker class has issue to update the token into server due to context value. You can check my code screenshots. I was assigned wrong context but later fixed it and now code is running perfectly.

    enter image description here