Using WorkManager in Android

Aseem Wangoo
Level Up Coding
Published in
7 min readAug 12, 2021

--

Using WorkManager in Android

Article here: https://flatteredwithflutter.com/using-workmanager-in-android/

We will cover briefly:

  1. Create Custom WorkManager
  2. Create OneTimeWorkRequest
  3. Create PeriodicWorkRequest
  4. Write Tests for Workers (step2 and step3)

Note: This article does not explain the working of WorkManager, but focuses on its use.

Using WorkManager in Android

Create Custom WorkManager

In case you are new to WorkManager, there is a detailed description here

As per the docs

By default, WorkManager configures itself automatically when your app starts. If you require more control of how WorkManager manages and schedules work, you can customise the WorkManager configuration.

  • Install the dependencies inside build.gradle of your app
def work_version = "2.5.0"implementation "androidx.work:work-runtime-ktx:$work_version"
androidTestImplementation "androidx.work:work-testing:$work_version"
  • Remove the default initialiser from AndroidManifest.xml
<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
tools:node="remove" />
  • Create your application class and define your own custom configuration.
class TodoApplication() : Application(), Configuration.Provider {
override fun onCreate() {
super.onCreate()
// LATER PUT THE PERIODIC WORK REQUEST HERE
}
override fun getWorkManagerConfiguration(): Configuration {

return if (BuildConfig.DEBUG) { Configuration.Builder().setMinimumLoggingLevel(Log.DEBUG).build()
}
else { Configuration.Builder().setMinimumLoggingLevel(Log.ERROR).build()
}
}
}

--

--