Home > Enterprise >  File downloading in an android app (with kotlin)
File downloading in an android app (with kotlin)

Time:08-24

I have been working on how to download a file (audio,image,...) from the internet using DownloadManager and BroadcastReceiver. Though I have made some progress and got some results, it is still not fully working and I can't find a good tutorial for what I need to do.

I got to the point where I get a signal in the onReceive() method of the BroadcastReceiver telling me that the download is complete. But I don't know how to make use of the result, I mean access the actual file for example to play an audio or display an image (or do whatever with the file).

Here is the relevant code for the problem:

    var brdCstRcvr = object:BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            val id = p1?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)

            if (id == downloadID) {
                Toast.makeText(applicationContext,"Download Completed !!!",
                    Toast.LENGTH_LONG).show()
                val mgr = applicationContext.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
                val uri:Uri = mgr.getUriForDownloadedFile(downloadID)

                println("URI=" uri.toString())
                println("URI-Path=" uri.path)
                // What to do here to make use of the downloaded file?
            }
        }
    }

When running the app, the code above executes: I can see the message "Download Completed !!!". I can also see the results of the 2 println lines in the console. What I need is to know how to use what I have to get access to the actual file. I have tried a few things that I found reading the net, but to no avail.

CodePudding user response:

If I'm reading this correctly, you're successfully downloading the file, and getting the URI. Depending on the location of that file (like if it's on external storage), you may have to deal with file access permission APIs. But in short, all you need is:

var file = File(uri.getPath())

CodePudding user response:

You access a file using its uri by opening an inputstream for the uri and then read the content from the stream.

 InputStream is = getContentResolver().openInputStream(uri):

And uri.getPath() does not give a file system path

  • Related