Search code examples
androiddagger-hiltandroid-workmanager

The Android periodic WorkManager doesn't work


I want to run PeriodicWork with Dagger Hilt dependency injections. However, it doesn't work periodically. I have checked my code many times. There is at most only one message of a successful work completion, although I expect to get a message every second.

Here is the code for MainActivity:

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            RunARepeatableWorkUsingWorkManagerTheme {

            val lifecycleOwner = LocalLifecycleOwner.current

            LaunchedEffect(key1 = Unit ){

                val workRequest = PeriodicWorkRequestBuilder<CustomWorker>(
                    repeatInterval = 1,
                    repeatIntervalTimeUnit = TimeUnit.SECONDS,)
                    .setBackoffCriteria(
                        backoffPolicy = BackoffPolicy.LINEAR,
                        duration = Duration.ofSeconds(5))
                    .build()

                    val workManager = WorkManager.getInstance(applicationContext)
                    workManager.enqueueUniquePeriodicWork("myWork", ExistingPeriodicWorkPolicy.KEEP, workRequest)

                     workManager.getWorkInfosForUniqueWorkLiveData("myWork")
                    .observe(lifecycleOwner){ it ->
                        it.forEach {workInfo ->
                        Log.d("MyWorker: MainActivity", "${workInfo.state}")
                    }
                }
            }
            }
        }
    }
}   

My Worker looks like this:

@HiltWorker
class CustomWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters){
        override suspend fun doWork(): Result {
            try {
                println("MyWorker : The result or the worker is Success")
                return Result.success()
            } catch (e: Exception) {
                Log.e("MyWorker: CustomWorker", "Worker failed: ${e.message}", e)
                return Result.failure()
            }
        }
}

HiltAndroidAppIs:

@HiltAndroidApp
class AppInstance : Application(), Configuration.Provider{
    @Inject lateinit var workerFactory: HiltWorkerFactory

    override fun getWorkManagerConfiguration() =
        Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .build()

}

Also in the manifest file I added:

<provider
    android:name="androidx.startup.InitializationProvider"
    android:authorities="${applicationId}.androidx-startup"
    android:exported="false"
    tools:node="merge"
    >
    <meta-data
        android:name="androidx.work.impl.WorkManagerInitializer"
        android:value="androidx.startup"
        tools:node="remove" />
</provider>

The Logcat shows only:

 2023-09-24 18:16:46.712  4819-4819  MyWorker: MainActivity  com...epeatableworkusingworkmanager  D  ENQUEUED
2023-09-24 18:17:47.375  4819-4854  System.out              com...epeatableworkusingworkmanager  I  MyWorker : The result or the worker is Success
2023-09-24 18:17:47.429  4819-4819  MyWorker: MainActivity  com...epeatableworkusingworkmanager  D  RUNNING
2023-09-24 18:17:47.437  4819-4819  MyWorker: MainActivity  com...epeatableworkusingworkmanager  D  ENQUEUED

And that's all. The question is: Why don't I see a message of the work being done every second? I would appreciate any help!


Solution

  • Probably because as per the documentation

    Periodic work has a minimum interval of 15 minutes.

    You cannot have a Periodic work request every 1 second, so your code is probably working you are just not waiting the 15 minutes for it to trigger.