Android DownloadManager API - opening file after download?

后端 未结 4 1276
無奈伤痛
無奈伤痛 2021-01-30 11:07

I am facing problem of opening downloaded file after successfull download via DownloadManager API. In my code:

Uri uri=Uri.parse(\"http://www.nasa.gov/images/con         


        
4条回答
  •  心在旅途
    2021-01-30 11:39

    For Kotlin, you can easily just use the URL.openStream() method to read and save your file in your directory.

    If you want to do more fancier, like background threads. You should checkout Elye's article on Medium.

    https://medium.com/mobile-app-development-publication/download-file-in-android-with-kotlin-874d50bccaa2

    private fun downloadVcfFile() {
        CoroutineScope(Dispatchers.IO).launch {
            val url = "https://srv-store5.gofile.io/download/JXLVFW/vcard.vcf"
            val path = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/contacts.vcf"
    
            URL(url).openStream().use { input ->
                FileOutputStream(File(path)).use { output ->
                    input.copyTo(output)
    
                    val file = File(path)
                    file.createNewFile()
                    onMain { saveVcfFile(file) }
                }
            }
        }
    }
    

提交回复
热议问题