android - DownloadManager 适用于 API 30,但不适用于 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")