DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Download Manager in Android: File Downloads with Progress Tracking

Android's DownloadManager provides a robust system for handling file downloads with progress notifications, retry logic, and system integration.

Basic Download Request

import android.app.DownloadManager
import android.net.Uri

val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

val request = DownloadManager.Request(Uri.parse("https://example.com/file.apk"))
    .setTitle("Downloading app")
    .setDescription("Please wait...")
    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "app.apk")
    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

val downloadId = downloadManager.enqueue(request)
Enter fullscreen mode Exit fullscreen mode

Tracking Progress

val query = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(query)

if (cursor.moveToFirst()) {
    val downloadedBytes = cursor.getLong(
        cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
    )
    val totalBytes = cursor.getLong(
        cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
    )
    val progress = (downloadedBytes.toFloat() / totalBytes * 100).toInt()
    updateProgressUI(progress)
}
cursor.close()
Enter fullscreen mode Exit fullscreen mode

Using OkHttp for More Control

val client = OkHttpClient()
val response = client.newCall(Request.Builder()
    .url("https://example.com/file.zip")
    .build()
).execute()

val inputStream = response.body?.byteStream()
val totalBytes = response.body?.contentLength() ?: 0
Enter fullscreen mode Exit fullscreen mode

Listening for Completion

val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L)
            if (id == downloadId) {
                onDownloadComplete()
            }
        }
    }
}

context.registerReceiver(receiver, 
    IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
    Context.RECEIVER_NOT_EXPORTED
)
Enter fullscreen mode Exit fullscreen mode

DownloadManager handles background downloads, retries, and Wi-Fi-only options automatically. For full progress control, consider OkHttp with custom interceptors.


8 Android app templates (Habit Tracker, Budget Manager, Task Manager, and more) available on Gumroad

Top comments (0)