我的应用程序中有一个简单的功能,用户可以下载文件,然后使用任何其他已安装的应用程序打开或共享。在 android Q 之前,我对此没有任何问题,但是随着新的隐私更改,我不知道如何正确执行此操作。
我需要执行以下两个步骤:
要将文件下载到公共(public)下载文件夹,我使用下一个代码
val request = DownloadManager.Request(config.uri)
.setTitle(title)
.setDescription(config.description)
.setNotificationVisibility(notificationVisibility)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename.pdf")
val downloadId = downloadManager.enqueue(request)
下载完成后,我得到下载的文件 Uri 像这样
val query = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(query)
val fileUriStr = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
val fileUri = Uri.parse(fileUriStr)
最后,当用户单击“打开”按钮时,我创建了下一个 Intent
val mime = context.contentResolver.getType(fileUri)
val intent = Intent()
.setAction(Intent.ACTION_VIEW)
.setDataAndType(uri, mime)
.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
所有这些解决方案在 Android Q 之前都可以正常工作。在 Intent 启动后的 android Q 上,我看到选择目标应用程序的对话框,当我选择目标应用程序时,我收到此应用程序无法访问文件的错误(我使用 Adobe Reader 作为目标应用程序)。
那么,问题是如何在 Android 10 上正确执行此操作?
P/S/对不起我的英语不好
最佳答案
我有同样的问题。我用了DownloadManager.getUriForDownloadedFile()
而不是 Uri
从查询返回,问题解决了!我不知道究竟是什么导致了这个问题,但我发现这个解决方案不适用于较低的版本。所以我结束了这一行:
var fileUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) downloadManager.getUriForDownloadedFile(requestId) else Uri.parse(fileUriStr)
我也从这里得到了 mime 类型:val mime = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE))
它适用于所有版本。
关于android - 为什么我无法在 Android Q 上打开下载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60931912/