Using Android DownloadManager for reliable file downloads

Android’s DownloadManager is the built-in system service for transferring files over HTTP or HTTPS. It queues requests, continues work while an app is backgrounded, reports progress, and can show a notification when the file is ready. It suits downloadable PDFs, images, audio, documents, and other user-requested assets.

It is not a replacement for every network client. Authentication handshakes, streaming APIs, and small requests often work better with OkHttp. The design must also decide where the file lives, how failures appear, and whether users can access the finished file outside the app.

Comparing download mechanisms

Pick a mechanism according to the job the file performs, rather than treating every transfer as the same task.

Mechanism Best suited to Main advantage Main constraint
DownloadManager Large, user-visible files OS-managed queue and notifications Limited control of request lifecycle
OkHttp or Retrofit APIs, authenticated requests, and streaming Full control of headers and responses App manages retries and background work
WorkManager Deferred or guaranteed application work Survives restarts and supports constraints Not designed as a file downloader

DownloadManager fits durable file transfers because the operating system owns the queue, retry behaviour, progress, and notification. Use OkHttp for custom network flows and WorkManager for deferrable app work. For a conventional download that can continue after the user leaves the screen, DownloadManager is usually the simplest choice.

Enqueuing and configuring a download

Add the INTERNET permission to the manifest, then create a request from a validated HTTPS URL. Keep the numeric ID returned by enqueue; it is the handle for tracking and cancelling the transfer.

val request = DownloadManager.Request(Uri.parse(url)).apply {
    setTitle("Annual report")
    setDescription("Saving to the app download folder")
    setMimeType("application/pdf")
    setNotificationVisibility(
        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
    )
    setDestinationInExternalFilesDir(
        context,
        Environment.DIRECTORY_DOWNLOADS,
        "annual-report.pdf"
    )
}
val manager = context.getSystemService(DownloadManager::class.java)
val downloadId = manager.enqueue(request)

This destination is app-specific external storage. It avoids broad storage permissions on current Android releases and suits a file that the app will open or share. To place a copy in the public Downloads collection, use the public-destination API only after checking support across the app’s minimum Android versions and scoped-storage behaviour.

enqueue can reject an invalid request, so catch failures and show a clear message. Set metered and roaming preferences to match the product’s data policy, especially when a transfer must not consume a customer’s limited mobile-data allowance.

Tracking progress and completion

Store the download ID with the item shown in the interface, such as in saved state or preferences. Querying by that ID lets the app recover after process death and avoids creating a duplicate request.

val query = DownloadManager.Query().setFilterById(downloadId)
manager.query(query)?.use { cursor ->
    if (cursor.moveToFirst()) {
        val status = cursor.getInt(
            cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)
        )
    }
}

Register a receiver for DownloadManager.ACTION_DOWNLOAD_COMPLETE while the relevant screen is active. Its EXTRA_DOWNLOAD_ID identifies the request, but completion still needs confirmation through the status query. A dynamic receiver ends with the app’s active lifetime, so query outstanding IDs whenever the app returns to the foreground.

Read COLUMN_BYTES_DOWNLOADED_SO_FAR and COLUMN_TOTAL_SIZE_BYTES at a sensible interval for a progress bar. Let the system notification show detailed live progress; an app should not start a foreground service merely to duplicate that function.

Recovering from failures and network changes

A queued request can pause while waiting for a network and later resume. Use COLUMN_STATUS and COLUMN_REASON to distinguish a paused transfer from a final failure, then tailor the message for HTTP errors, expired links, low storage, and malformed URLs. Calling remove(downloadId) cancels the request and removes its managed download.

Network changes are routine. A train commute through Sydney or Melbourne can alternate between cellular coverage and station Wi-Fi, while regional Australians may depend on fixed NBN connections where available, mobile broadband, or both. A managed queue waits for service instead of forcing users to restart large transfers.

Some prepaid and budget mobile plans use capped or shaped mobile data, with provider-specific extra-data rules. Respect the user’s metered-network choice, explain when a transfer is waiting, and make cancellation obvious so a large document does not unexpectedly consume an allowance.

Storing files safely and privately

App-specific external storage gives the app a simple download location without general access to the device. It is removed when the app is uninstalled, making it suitable for working copies and files opened inside the app. Use public Downloads storage only when users are expected to find and keep the file there.

Share app-specific files through a FileProvider content URI, not a raw file:// URI. Sanitise server-provided filenames by removing directory separators and traversal sequences, and verify a supplied checksum. These measures help prevent path attacks and corrupted or malicious content.

For organisations covered by the Privacy Act 1988 and the Australian Privacy Principles, downloaded records can still contain personal information. Keep transport on HTTPS, avoid personal details in notifications, apply a defensible retention period, and remove cached copies when they are no longer needed. Downloading a file does not remove the organisation’s privacy obligations.

The Copyright Act 1968 matters when an app offers books, recordings, images, or licensed material. Distribute only content the app is authorised to provide, respect licences and geo-restrictions, and avoid presenting a copy as unrestricted merely because it can be saved locally.

Testing on real Australian conditions

Test on the Android versions and devices customers use, including Samsung Galaxy and Google Pixel models sold in Australia. Exercise app-specific and public destinations, notification settings, low storage, background use, cancellation, and both successful and failed responses. A small suite of repeatable checks can sit beside download behaviour test notes to keep the same cases visible.

Include real network transitions: Wi-Fi to mobile data, a brief loss of service, and reconnection through a fixed connection. These cases reflect use during a commute and in regional areas where fixed NBN coverage may be unavailable. Verify that metered-network preferences still behave as intended.

Do not test only a fresh install. Restore saved IDs, reopen the app after the process has been killed, and try a completed file on another device. Comparing the returned status, reason, filename, and bytes confirms that recovery works beyond the happy path.

Delivering a clear download experience

Give users the filename, expected size, progress, and a visible cancel action. When a transfer succeeds, offer Open and Share through Android’s standard chooser; when it fails, preserve the request details so Retry can create a fresh, valid download.

For Australian-facing file names, use an unambiguous DD/MM/YYYY date and remember that the country spans several time zones and observes daylight-saving changes in the southern states. Let Android format user-facing times with an Australian locale instead of hard-coding an offset.

Start with one HTTPS file in a test screen, handle success and failure, verify that the result opens safely, and build from that working flow.