Skip to content

Instantly share code, notes, and snippets.

@sajjadyousefnia
Created June 16, 2024 17:24
Show Gist options
  • Select an option

  • Save sajjadyousefnia/fc459dce2986e223784685c01f1b118b to your computer and use it in GitHub Desktop.

Select an option

Save sajjadyousefnia/fc459dce2986e223784685c01f1b118b to your computer and use it in GitHub Desktop.
val request = DownloadManager.Request(Uri.parse(url))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename.ext")
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
val manager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = manager.enqueue(request)
val query = DownloadManager.Query().setFilterById(downloadId)
var isDownloading = true
while (isDownloading) {
val cursor = manager.query(query)
if (cursor.moveToFirst()) {
val bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
val bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false
}
if (bytesTotal > 0) {
val progress = (bytesDownloaded * 100L / bytesTotal).toInt()
listener?.onProgress(progress)
}
}
cursor.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment