WorkManager and Glance Widgets
What is WorkManager?
WorkManager runs deferrable and guaranteed background work: syncing data, uploading logs, backing up. Work survives app restarts and reboots, and Android picks a good time based on battery and network.
A Worker
kotlin
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
return try {
val userId = inputData.getInt("userId", 0)
repository.sync(userId)
Result.success(workDataOf("synced" to true))
} catch (e: IOException) {
if (runAttemptCount < 3) Result.retry() else Result.failure()
}
}
}
Schedule It
kotlin
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
// run once
val oneTime = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(constraints)
.setInputData(workDataOf("userId" to 42))
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context).enqueueUniqueWork("sync-once", ExistingWorkPolicy.KEEP, oneTime)
// repeat (minimum interval is 15 minutes)
val periodic = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS).setConstraints(constraints).build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork("sync-hourly", ExistingPeriodicWorkPolicy.UPDATE, periodic)
Observe Progress
kotlin
val info by WorkManager.getInstance(context)
.getWorkInfoByIdFlow(oneTime.id)
.collectAsStateWithLifecycle(initialValue = null)
Text("State: ${info?.state}")
| Need | Use |
|---|---|
| Guaranteed background work, can wait | WorkManager |
| Work while the app is open | Coroutines in viewModelScope |
| Ongoing task the user knows about | Foreground service |
| Exact time alarm | AlarmManager (with care) |
Widgets with Jetpack Glance
Glance lets you build home screen widgets with Compose-like code.
kotlin
implementation(libs.androidx.glance.appwidget)
implementation(libs.androidx.glance.material3)
kotlin
class StreakWidget : GlanceAppWidget() {
override suspend fun provideGlance(context: Context, id: GlanceId) {
val streak = context.getSharedPreferences("app", Context.MODE_PRIVATE).getInt("streak", 0)
provideContent {
GlanceTheme {
Column(
modifier = GlanceModifier.fillMaxSize().background(GlanceTheme.colors.widgetBackground).padding(12.dp),
verticalAlignment = Alignment.Vertical.CenterVertically,
horizontalAlignment = Alignment.Horizontal.CenterHorizontally
) {
Text("Study streak", style = TextStyle(fontSize = 14.sp))
Text("$streak days", style = TextStyle(fontSize = 28.sp, fontWeight = FontWeight.Bold))
Button(text = "Open", onClick = actionStartActivity<MainActivity>())
}
}
}
}
}
class StreakWidgetReceiver : GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = StreakWidget()
}
// Update the widget from your app
StreakWidget().updateAll(context)
xml
<receiver android:name=".StreakWidgetReceiver" android:exported="true">
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/streak_widget_info" />
</receiver>
Widget info file: Create
res/xml/streak_widget_info.xml with appwidget-provider settings such as minimum size, update period and preview. Android Studio has a template: New > Widget > App Widget.
Limits: Widgets update on a limited budget. Avoid constant refreshes and update from your app or WorkManager when the data really changes.
Conclusion
WorkManager runs reliable background jobs with constraints and retries. Glance builds widgets with Compose-style code.
Quick Summary: Create a CoroutineWorker, enqueue with constraints, use unique work, and build widgets with GlanceAppWidget.

