DownloadManager 适用于 API 30 但不适用于 API 27

DownloadManager works for API 30 but no for API 27

我正在尝试从服务器下载一个 pdf 文件(我有 url),我正在尝试这个解决方案

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)
}

这适用于 API 30 但不适用于 API 27,我不知道为什么。 有人可以帮我吗?

更新: 我认为这可能是权限问题,因为我在 API 27 中再次尝试并在日志 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.

中看到了这一点

我能够解决问题,我更改了这一行 request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS, fileName) 对于我用下载文件夹的地址和文件名解析的 uri,我将其设置为 request.setDestinationUri (destinationUri)

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