Search code examples
androidkotlinandroid-download-manager

DownloadManager works for API 30 but no for API 27


I am trying to download a pdf file from the server (I have the url), and I am trying this solution

fun downloadPDF(url: String?, fileName: String): ResponseStatus {
        val uri = Uri.parse(url)
        val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager?
        val request = DownloadManager.Request(uri)
        request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE
        )
        request.setTitle(fileName)
        request.setDescription("Android Data download using DownloadManager.")
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
        request.setMimeType("*/*")
        if (downloadManager == null) {
            return ResponseStatus.Error( context.getString(R.string.download_error) )
        }
        downloadManager.enqueue(request)
        return ResponseStatus.OK(uri)
}

this works for API 30 but not for API 27 and I don't know why. Can someone help me please?

UPDATE: I think that this can be a permissions problem because I tried again in API 27 and see this in the log java.lang.SecurityException: No permission to write to /storage/emulated/0/Download/file name12-34: Neither user 10080 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.


Solution

  • I was able to solve the problem, I changed this line request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS, fileName) for a uri that I parse with the address of the download folder and the file name, and I set it with request.setDestinationUri (destinationUri)

    val destination = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() +
                    "/" + fileName
    val destinationUri = Uri.parse("$FILE_BASE_PATH$destination")