First let me correct please :
Work Manager : The minimum repeat interval that can be defined is 15 minutes (same as the JobScheduler API). If this is not correct please let me know.
I have created below class for executing periodic work request :
object WorkManagerUtils {
fun syncWorkManager() {
val myConstraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val syncRequest = PeriodicWorkRequest
.Builder(MyWorker::class.java, 20000, TimeUnit.MILLISECONDS)
.setConstraints(myConstraints)
.build()
WorkManager
.getInstance()
.enqueueUniquePeriodicWork(
Constants.WORKER,
ExistingPeriodicWorkPolicy.KEEP,
syncRequest)
}
}
Below is my Worker class. Please check :
class MyWorker(val context: Context, param: WorkerParameters) : Worker(context, param) {
override fun doWork(): Result {
if (isNetworkAvailable(context)) {
callSyncApi()
} else {
WorkManagerUtils.syncWorkManager()
}
return Result.success()
}
private fun callSyncApi() {
ToastUtils.shortToast(0,"This is working")
}
}
Calling this in my Activity as below :
WorkManagerUtils.syncWorkManager()
You can notice that currently I am just displaying toast as my work. I want to check that is this working or not ?
But the toast is not displaying.
Any interval under 15 minutes will be replaced by 15 minutes.
Assuming your
ToastUtils.showToast(...)
works, I believe work manager chose 15 minutes of interval and the “KEEP” existing work policy prevented rescheduling and testing.I suggest while testing change the existing work policy to “REPLACE”.
From work manager 1.0.0 source:
There is an overload of
setPeriodic
function which applies the same interval enforcement.