Skip to content

Instantly share code, notes, and snippets.

@labibmuhajir
Created June 3, 2021 08:11
Show Gist options
  • Save labibmuhajir/4977d52723f34cab259f333d7fa0f545 to your computer and use it in GitHub Desktop.
Save labibmuhajir/4977d52723f34cab259f333d7fa0f545 to your computer and use it in GitHub Desktop.
Android Download Manager
class DownloadManager(private val context: Context) {
fun download(url: String, fileName: String) {
try {
val uri = Uri.parse(url)
val downloadRequest = DownloadManager.Request(uri).apply {
val extension = MimeTypeMap.getFileExtensionFromUrl(url)
val name = "$fileName.$extension"
setTitle(name)
setAllowedOverMetered(true)
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name)
}
val downloadManager =
context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = downloadManager.enqueue(downloadRequest)
if (downloadId != 0L) {
context.shortToast(R.string.lifepack_downloading)
}
val br = object: BroadcastReceiver(){
override fun onReceive(p0: Context?, p1: Intent?) {
val id = p1?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (downloadId == id) {
context.shortToast(R.string.lifepack_download_complete)
}
}
}
context.registerReceiver(br, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
} catch(e: Exception) {
context.shortToast(e.localizedMessage)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment