Android通过Intent打开外部存储PDF文件无响应问题排查
问题排查与解决
核心问题原因
- Intent参数传递错误:代码中通过
intent.putExtra(Intent.ACTION_VIEW, uri)传递Uri是错误的,ACTION_VIEW意图需要通过setData()或setDataAndType()指定目标内容Uri,而非putExtra。 - 缺少Uri访问权限:你使用的
/document/primary:11796018.pdf是MediaStore的内容Uri,目标应用默认没有权限访问该Uri,必须显式授予临时读取权限。 - 配置文件语法错误:AndroidManifest和file_paths.xml存在标签未闭合的语法问题,虽然不是当前问题的直接诱因,但会导致FileProvider功能失效(若后续处理本地文件时会用到)。
解决方法
1. 修正打开文件的核心代码
替换原代码为以下实现,正确设置Intent并添加权限标记:
val sfile: String = "/document/primary:11796018.pdf" val uri = Uri.parse(sfile) val intent = Intent(Intent.ACTION_VIEW).apply { // 正确设置数据Uri和MIME类型 setDataAndType(uri, "application/pdf") // 授予目标应用临时读取权限 addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(Intent.createChooser(intent, "Open file"))
2. 修正FileProvider配置语法错误
AndroidManifest.xml修正:
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
(补全<provider>标签的闭合>)
file_paths.xml修正:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
(补全<paths>标签的闭合>)
注:FileProvider配置是用于处理本地文件路径转内容Uri的场景,当前问题中的Uri属于MediaStore内容Uri,无需经过FileProvider转换,修正配置是为了避免后续功能异常。
内容的提问来源于stack exchange,提问作者Darius da costa
相关产品推荐
相关产品推荐

