I am following the Udacity Android Kotlin Developer course. In one of the lessons, the instructor taught about doing background tasks using WorkManager always to cache data in the background to show fresh data at the app's start.
So the code to start WorkManager refreshing data periodically is defined in the Main Application of the app.
class DevByteApplication : Application() {
/**
* onCreate is called before the first screen is shown to the user.
*
* Use it to setup any background tasks, running expensive setup operations in a background
* thread to avoid delaying app start.
*/
val applicationScope = CoroutineScope(Dispatchers.Default)
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
delayedInit()
}
private fun delayedInit() = applicationScope.launch {
setupRecurringWork()
}
private fun setupRecurringWork() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresBatteryNotLow(true)
.setRequiresCharging(true)
.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setRequiresDeviceIdle(true)
}
}.build()
val repeatingRequest = PeriodicWorkRequestBuilder<RefreshDataWorker>(1, TimeUnit.DAYS)
.build()
WorkManager.getInstance().enqueueUniquePeriodicWork(
RefreshDataWorker.WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
repeatingRequest)
}}
Questions are:
So does WorkManager only start to work if an app is launched once? Or does it start to work once we install the application?
Also,
1. If we shut down the phone completely - will the WorkManager of our app work once we turn on the phone back 2. If we close the application completely - will the WorkManager still work?
If you have sources that talk specifically about these questions, I would love to read them!