How show ProgressBar and Completed listener in DownloadManager android

96 Views Asked by At

In my application I want use DownloadManager for download Image from server.
I write below codes and I can download image and show into gallery app.
But I want show ProgressBar when downloading and change state after download completed !
I write below codes, but I don't know how can I use ProgressBar and Completed listener!
My fun :

private fun downloadImageNew(filename: String, downloadUrlOfImage: String) {
        try {
            val dm = requireContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager?
            val downloadUri = Uri.parse(downloadUrlOfImage)
            val request = DownloadManager.Request(downloadUri)
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
                .setTitle(filename)
                .setMimeType("image/jpeg")
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, File.separator + filename + ".jpg")
            dm!!.enqueue(request)
            Toast.makeText(requireContext(), "Image download started.", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "Image download failed.", Toast.LENGTH_SHORT).show()
        }
    } 

How can I add this 2 features to my downloader fun ?

1

There are 1 best solutions below

2
Anna Andreeva Rogotulka On BEST ANSWER

You need to:

1 save the id returned from downloadManager.enqueue function;

2 register a BroadcastReceiver with an DownloadManager.ACTION_DOWNLOAD_COMPLETE IntentFilter. Inside its onReceive function, check the id from 1. to match the id from the intent.

val receiver =
    object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (id == yourSavedDownloadId) {
                // download is complete
            }
        }
    }