Android
Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
WorkManager handles lifecycle and retry logic. DownloadManager handles reliable HTTP transfers. Used together, each does what it is good at. This post covers the coroutine polling loop that bridges them in production.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 5 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
WorkManager and DownloadManager are often treated as alternatives. They are
not. WorkManager manages work lifecycle — constraints, retries, chaining,
cancellation. DownloadManager manages reliable HTTP file transfers — system-level
download queue, OS notifications, background continuation even when the app
process is killed. Used together, DownloadFilesWorker uses WorkManager to
orchestrate the operation and DownloadManager to execute the transfers.
The interesting part is the coroutine polling loop that bridges the two.
Prerequisites
WorkManager 2.11.1, Kotlin Coroutines 1.8.1, Hilt 2.56.
The Hilt + WorkManager setup from Part 1 is assumed. DownloadManager is a
system service — no additional dependency.
Background
DownloadManager does not expose a suspend API or a Flow. It exposes a
Cursor-based query interface for checking download status. The worker polls
that cursor on a 5-second interval, up to an 8-minute deadline, and resolves
to one of three outcomes: all succeeded, some failed, or timed out.
WorkManager handles what happens after: AllSucceeded triggers the database
seeding chain; TimedOut returns Result.retry() so WorkManager backs off
and retries; SomeFailed returns Result.failure() with the failed file names
attached as output data.
Implementation
1. Worker structure
The worker fetches URLs from the backend, enqueues each file with DownloadManager,
then awaits completion of all downloads before handing off to the database
seeding pipeline.
@HiltWorkerclass DownloadFilesWorker @AssistedInject constructor( @Assisted val context: Context, @Assisted workParameters: WorkerParameters, private val dataStore: BrickworkDataStore, private val workManagerUtil: WorkManagerUtil, private val repository: StoreRepository) : CoroutineWorker(context, workParameters) {
companion object { const val KEY_PROGRESS = "download_progress" const val KEY_FAILED_FILES = "failed_files" // WorkManager stops a worker after 10 minutes; leave room to clean up. private const val MAX_WAIT_MS = 8 * 60 * 1000L // 8 minutes private const val POLL_INTERVAL_MS = 5_000L // 5 seconds }MAX_WAIT_MS and POLL_INTERVAL_MS are constants, not magic numbers in the
loop. The deadline is deliberately under 10 minutes: that is the execution
window the system gives a non-foreground worker before stopping it. A
10-minute deadline would never fire — the worker would be stopped first, with
no chance to clean up its downloads.
2. Fetch URLs and enqueue downloads
override suspend fun doWork(): Result { val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val urls = when (val response = repository.generateUrl()) { is Resource.Success -> response.data.urls is Resource.Failure -> { Timber.e("Failed to fetch URLs: ${response.error}") return Result.retry() } }
if (urls.isEmpty()) { Timber.e("Server returned an empty URL list") return Result.failure() }
val pendingDownloads = urls.mapNotNull { urlEntry -> val downloader = Downloader( context = context, title = "Downloading ${urlEntry.name.uppercase()}", fileName = "${urlEntry.name}.json" ) val id = downloader.downloadFile(urlEntry.url) if (id == Downloader.DOWNLOAD_FAILED) null else DownloadTask(id = id, name = urlEntry.name) }
if (pendingDownloads.isEmpty()) { Timber.e("No downloads could be enqueued — DownloadManager may be disabled") return Result.failure() }A network failure fetching the URL list returns Result.retry() — the
backend may be temporarily unavailable. An empty URL list or a completely
disabled DownloadManager returns Result.failure() — those are not
transient conditions.
3. The polling loop
private suspend fun awaitDownloads( downloadManager: DownloadManager, tasks: List<DownloadTask>): DownloadResult { val pending = tasks.toMutableList() val failed = mutableListOf<String>() val deadline = System.currentTimeMillis() + MAX_WAIT_MS val total = tasks.size
while (pending.isNotEmpty()) { if (System.currentTimeMillis() > deadline) { return DownloadResult.TimedOut(pending.map { it.name }) }
val justFinished = mutableListOf<DownloadTask>()
pending.forEach { task -> val query = DownloadManager.Query().setFilterById(task.id) downloadManager.query(query).use { cursor -> if (!cursor.moveToFirst()) { Timber.e("Download record missing: ${task.name}") failed += task.name justFinished += task return@use }
val status = cursor.getInt( cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS) ) when (status) { DownloadManager.STATUS_SUCCESSFUL -> justFinished += task
DownloadManager.STATUS_FAILED -> { val reason = cursor.getInt( cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON) ) Timber.e("Failed: ${task.name}, reason: $reason") failed += task.name justFinished += task }
else -> { // RUNNING, PAUSED, PENDING val downloaded = cursor.getLong( cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR) ) val totalBytes = cursor.getLong( cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES) ) if (totalBytes > 0) { val pct = (downloaded * 100 / totalBytes).toInt() Timber.d("Progress ${task.name}: $pct%") } } } } }
pending.removeAll(justFinished)
val completed = total - pending.size setProgress(workDataOf(KEY_PROGRESS to (completed * 100 / total)))
if (pending.isNotEmpty()) delay(POLL_INTERVAL_MS) }
return if (failed.isEmpty()) DownloadResult.AllSucceeded else DownloadResult.SomeFailed(failed)}.use { cursor -> } ensures the cursor is closed after each poll cycle.
Leaving cursors open across loop iterations leaks cursor windows, and a long
poll eventually fails with CursorWindowAllocationException.
setProgress() emits the aggregate completion percentage as WorkInfo progress
data, readable from the UI via WorkInfo.progress.getInt(KEY_PROGRESS, 0).
4. Sealed result and dispatch
return when (val result = awaitDownloads(downloadManager, pendingDownloads)) { is DownloadResult.AllSucceeded -> { dataStore.setIsFirstInstall(false) workManagerUtil.writeAllToDatabaseWithDependencies() Result.success() } is DownloadResult.SomeFailed -> { Result.failure( workDataOf(KEY_FAILED_FILES to result.failedNames.toTypedArray()) ) } is DownloadResult.TimedOut -> { // Remove what is still queued, or the retry will download everything twice. downloadManager.remove(*pendingDownloads.map { it.id }.toLongArray()) Result.retry() }}
private data class DownloadTask(val id: Long, val name: String)
private sealed interface DownloadResult { data object AllSucceeded : DownloadResult data class SomeFailed(val failedNames: List<String>) : DownloadResult data class TimedOut(val remainingNames: List<String>) : DownloadResult}AllSucceeded is the only branch that triggers writeAllToDatabaseWithDependencies().
The phased database seeding chain (covered in Part 3) only starts when every
file is confirmed present on disk.
Testing
./gradlew connectedAndroidTest --tests "*.DownloadFilesWorkerTest"
BUILD SUCCESSFUL in 21s5 instrumented tests completedTest the timeout path by mocking DownloadManager.query() to always return
STATUS_RUNNING and setting MAX_WAIT_MS to a small value via test configuration.
Assert that doWork() returns Result.retry().
Pitfalls
Production considerations
The 5-second poll interval is a balance between responsiveness and battery
impact. For large files over mobile data, 10-15 seconds is more appropriate.
For a local Wi-Fi scenario (inventory sync on a shop floor), 2 seconds is
reasonable. Make POLL_INTERVAL_MS a buildConfigField if you need to tune
it per environment.
The 8-minute deadline assumes the worst-case download on the slowest expected connection. A set of seven JSON files totalling ~50MB over a 1Mbps connection takes roughly 7 minutes, which is uncomfortably close. If your files are larger, don’t raise the deadline past the 10-minute window: see the next section.
Wrapping up
You now have a WorkManager worker that uses DownloadManager for reliable file transfer, a sealed result type that maps to distinct WorkManager outcomes, and a coroutine polling loop that suspends rather than blocks. The database seeding pipeline starts only after every file is confirmed on disk.
Going deeper
Stop polling: react to completion instead. The system broadcasts
DownloadManager.ACTION_DOWNLOAD_COMPLETE for each finished download. A
cleaner design for large files is two-step: the worker enqueues the downloads,
stores their IDs in DataStore and returns success(). A BroadcastReceiver
(or a short follow-up worker it enqueues) checks whether every stored ID has
finished and then starts the seeding chain. Nothing waits, so the 10-minute
limit stops mattering.
Or make the worker long-running. If you keep the polling design, call
setForeground(createForegroundInfo()) at the start of doWork(). A
foreground worker is not bound by the 10-minute window. On Android 14+ declare
android:foregroundServiceType="dataSync" for WorkManager’s
SystemForegroundService in the manifest.
Survive process death between steps. WorkManager may kill and re-run the worker. Persisting download IDs (rather than holding them only in memory) lets a re-run attach to downloads already in progress instead of starting new ones. Query by ID first, enqueue only what is missing.
Verify what you downloaded. A successful status means bytes arrived, not that they are the right bytes. Have the backend return a SHA-256 per file alongside the URL and verify before seeding. A truncated JSON file that parses partially is worse than a failed download.