Offline-first architecture with WorkManager for background sync, periodic tasks, and constraints.
WorkManager Overview
# Dependencies
implementation("androidx.work:work-runtime-ktx:2.9.0")
implementation("androidx.work:work-rxjava3:2.9.0") // Optional RxJava
androidTestImplementation("androidx.work:work-testing:2.9.0")Basic Worker
// CoroutineWorker (recommended)
class SyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val repository: SyncRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
return try {
val lastSync = inputData.getLong("last_sync", 0)
val result = repository.syncData(lastSync)
// Output data for chaining
val outputData = workDataOf(
"synced_count" to result.count,
"last_sync" to result.timestamp
)
Result.success(outputData)
} catch (e: Exception) {
// Retry with exponential backoff
Result.retry()
}
}
}
// Worker Factory for Hilt
@HiltWorkerFactory
class HiltWorkerFactory @Inject constructor(
context: Context,
private val workerFactory: androidx.work.Configuration.Provider
) : WorkerFactory() {
// Hilt handles injection automatically
}Worker with Constraints
// Define work request with constraints
fun scheduleSyncWork(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
.setRequiresBatteryNotLow(true)
.setRequiresStorageNotLow(true)
.build()
val inputData = workDataOf(
"last_sync" to getLastSyncTime()
)
val workRequest = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(constraints)
.setInputData(inputData)
.setBackoffCriteria(
BackoffPolicy.EXPONENTIAL,
15, TimeUnit.MINUTES
)
.addTag("sync")
.build()
WorkManager.getInstance(context).enqueue(workRequest)
}
// Periodic work (minimum 15 minutes)
fun schedulePeriodicSync(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
val periodicWork = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.addTag("periodic_sync")
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"periodic_sync",
ExistingPeriodicWorkPolicy.KEEP,
periodicWork
)
}Chaining Workers
// Chain: Download -> Process -> Save -> Notify
fun scheduleSyncChain(context: Context) {
val downloadWork = OneTimeWorkRequestBuilder<DownloadWorker>()
.setInputData(workDataOf("url" to "https://api.example.com/data"))
.build()
val processWork = OneTimeWorkRequestBuilder<ProcessWorker>()
.build()
val saveWork = OneTimeWorkRequestBuilder<SaveWorker>()
.build()
val notifyWork = OneTimeWorkRequestBuilder<NotifyWorker>()
.build()
WorkManager.getInstance(context)
.beginWith(downloadWork)
.then(processWork)
.then(saveWork)
.then(notifyWork)
.enqueue()
}
// Parallel then converge
fun scheduleParallelWork(context: Context) {
val fetchUsers = OneTimeWorkRequestBuilder<FetchUsersWorker>().build()
val fetchPosts = OneTimeWorkRequestBuilder<FetchPostsWorker>().build()
val fetchComments = OneTimeWorkRequestBuilder<FetchCommentsWorker>().build()
val mergeWork = OneTimeWorkRequestBuilder<MergeDataWorker>().build()
WorkManager.getInstance(context)
.beginWith(listOf(fetchUsers, fetchPosts, fetchComments))
.then(mergeWork)
.enqueue()
}CoroutineWorker with Progress
class UploadWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val apiService: ApiService,
private val fileRepository: FileRepository
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val fileId = inputData.getString("file_id") ?: return Result.failure()
val file = fileRepository.getFile(fileId) ?: return Result.failure()
val totalBytes = file.size
var uploadedBytes = 0L
return try {
apiService.uploadFile(file.path).collect { response ->
when (response) {
is UploadResponse.Progress -> {
uploadedBytes = response.bytesUploaded
// Report progress (10% increments)
val progress = (uploadedBytes * 100 / totalBytes).toInt()
if (progress % 10 == 0) {
setProgressAsync(workDataOf("progress" to progress))
}
}
is UploadResponse.Success -> {
fileRepository.markSynced(fileId)
return@collect Result.success(
workDataOf("file_id" to fileId)
)
}
is UploadResponse.Error -> {
return@collect Result.retry()
}
}
}
Result.success()
} catch (e: Exception) {
Result.retry()
}
}
}
// Observe progress in UI
fun observeUploadProgress(context: Context, workId: String) {
WorkManager.getInstance(context)
.getWorkInfoByIdLiveData(workId)
.observe(this) { workInfo ->
workInfo?.progress?.getInt("progress", 0)?.let { progress ->
// Update UI
binding.progressBar.progress = progress
}
}
}Offline-First Repository
class SyncRepositoryImpl @Inject constructor(
private val apiService: ApiService,
private val localDao: LocalDao,
private val workManager: WorkManager
) : SyncRepository {
// Local-first: read from DB, observe changes
override fun getItems(): Flow<List<Item>> {
return localDao.getAllItems()
.map { it.map { it.toDomain() } }
}
// Queue for sync when online
override suspend fun createItem(item: Item): Result<String> {
// 1. Save locally immediately
val id = UUID.randomUUID().toString()
val entity = item.toEntity(id, syncStatus = SyncStatus.PENDING)
localDao.insert(entity)
// 2. Schedule background sync
scheduleSyncWork()
return Result.Success(id)
}
override suspend fun updateItem(item: Item) {
val entity = item.toEntity(syncStatus = SyncStatus.PENDING)
localDao.update(entity)
scheduleSyncWork()
}
override suspend fun deleteItem(id: String) {
localDao.markDeleted(id)
scheduleSyncWork()
}
// Sync logic
override suspend fun syncData(since: Long): SyncResult {
val pendingItems = localDao.getPendingChanges(since)
var syncedCount = 0
for (item in pendingItems) {
when (item.syncAction) {
SyncAction.CREATE -> {
apiService.createItem(item.toCreateRequest())
.onSuccess { response ->
localDao.markSynced(item.id, response.serverId)
syncedCount++
}
}
SyncAction.UPDATE -> {
apiService.updateItem(item.serverId, item.toUpdateRequest())
.onSuccess { localDao.markSynced(item.id) }
}
SyncAction.DELETE -> {
apiService.deleteItem(item.serverId)
.onSuccess { localDao.delete(item.id) }
}
}
}
return SyncResult(syncedCount, System.currentTimeMillis())
}
private fun scheduleSyncWork() {
val work = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.addTag("sync")
.build()
workManager.enqueueUniqueWork("sync", ExistingWorkPolicy.REPLACE, work)
}
}
// Sync status tracking
enum class SyncStatus { SYNCED, PENDING, FAILED, DELETED }
enum class SyncAction { CREATE, UPDATE, DELETE }
data class SyncResult(val count: Int, val timestamp: Long)Testing Workers
@RunWith(AndroidJUnit4::class)
class SyncWorkerTest {
@get:Rule
val testRule = WorkManagerTestRule()
@Test
fun syncWorker_syncsData() = runTest {
// Given
val context = ApplicationProvider.getApplicationContext()
val workManager = WorkManager.getInstance(context)
// Set up test data in local DB
// ...
// Create worker input
val inputData = workDataOf("last_sync" to 0L)
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setInputData(inputData)
.build()
// Enqueue
workManager.enqueue(request).result.get()
// Get result
val workInfo = workManager.getWorkInfoById(request.id).get()
// Verify
assertEquals(WorkInfo.State.SUCCEEDED, workInfo.state)
val output = workInfo.outputData
assertTrue(output.getInt("synced_count", 0) > 0)
}
@Test
fun syncWorker_retriesOnFailure() = runTest {
val context = ApplicationProvider.getApplicationContext()
val workManager = WorkManager.getInstance(context)
// Mock API to fail
// ...
val request = OneTimeWorkRequestBuilder<SyncWorker>().build()
workManager.enqueue(request).result.get()
val workInfo = workManager.getWorkInfoById(request.id).get()
// Should retry (state will be RUNNING then RETRY)
// Note: TestRule executes synchronously
}
}Advanced Patterns
// Foreground service for long-running work
class LongSyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val repository: SyncRepository
) : CoroutineWorker(context, params) {
private val notificationId = 123
private val channelId = "sync_channel"
override suspend fun doWork(): Result {
// Create notification channel
createNotificationChannel()
// Start foreground
val notification = NotificationCompat.Builder(applicationContext, channelId)
.setContentTitle("Syncing...")
.setProgress(100, 0, true)
.setSmallIcon(R.drawable.ic_sync)
.build()
setForegroundAsync(createForegroundInfo(notification))
return try {
// Long running work with progress updates
repository.fullSync { progress ->
val updatedNotification = notificationBuilder
.setProgress(100, progress, false)
.build()
setForegroundAsync(createForegroundInfo(updatedNotification))
}
Result.success()
} catch (e: Exception) {
Result.failure()
}
}
private fun createForegroundInfo(notification: Notification): ForegroundInfo {
return ForegroundInfo(notificationId, notification)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId, "Sync", NotificationManager.IMPORTANCE_LOW
)
val manager = applicationContext.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}
}
// WorkManager initialization (custom configuration)
class MyApplication : Application(), Configuration.Provider {
override fun getWorkManagerConfiguration(): Configuration {
return Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setWorkerFactory(HiltWorkerFactory(this))
.build()
}
}Try It
Add WorkManager dependency. Create CoroutineWorker. Schedule with constraints. Chain workers. Test with WorkManagerTestRule.
# Add to build.gradle.kts:
# implementation("androidx.work:work-runtime-ktx:2.9.0")
# androidTestImplementation("androidx.work:work-testing:2.9.0")WorkManager mastery
- Create CoroutineWorker with Hilt injection
- Schedule work with network and battery constraints
- Chain multiple workers (download → process → save)
- Implement periodic sync (15+ min intervals)
- Build offline-first repository with local DB
- Track sync status (pending/synced/failed)
- Test workers with WorkManagerTestRule
- Use foreground service for long uploads
WorkManager guarantees execution with constraints. Use CoroutineWorker for suspend functions. Constraints: network, charging, idle, battery. Chain with beginWith().then(). PeriodicWorkRequest min 15 min. Offline-first: write local, sync background. Test with WorkManagerTestRule.
Resources
- WorkManager: https://developer.android.com/topic/libraries/architecture/workmanager
- WorkManager Guide: https://developer.android.com/topic/libraries/architecture/workmanager/basics
- Testing: https://developer.android.com/topic/libraries/architecture/workmanager/testing
- Foreground Work: https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running