android - 使用 FileProvider Android 从可移动 SD 卡打开文件时出错
问题描述
我的目标是从任何内存中打开 pdf 文件。
我使用带有设备内存和可移动 SD 卡的 android 模拟器。
所以路径看起来像:
/storage/emulated/0/hts221.pdf - 设备内存
/storage/1317-231C/LPS22HB.pdf - 可移动 SD 卡
使用此代码打开文件(其中 fileName 是上述两个之一):
File file = new File(fileName);
Intent target = new Intent(Intent.ACTION_VIEW);
Uri fileURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
target.setDataAndType(fileURI,"application/pdf");
target.setFlags(target.getFlags() | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
Intent intent = Intent.createChooser(target, "Open File");
context.startActivity(intent);
AndroidManifest.xml
<provider android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
xml/provier_path
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
问题:
当我尝试从设备内存(/storage/emulated/0/hts221.pdf)打开 pdf 文件时 - 一切正常。
但是,当我尝试从 SD 卡(/storage/1317-231C/LPS22HB.pdf)打开 pdf 文件时 -应用程序崩溃:
W System.err: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/1317-231C/LPS22HB.pdf
W System.err: at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
W System.err: at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
我在这里想念什么?我猜问题出在 xml/provier_path 的某个地方。
我使用 Qt Android,但我认为在这种情况下这并不重要。
解决方案
添加
<root-path name="root" path="." />
到 xml/provider_path。现在这两个文件都可以正常工作。
推荐阅读
- java - 如何在get请求中传递几个参数
- amazon-ec2 - 重启 EC2 实例后,Scylla 无法挂载 RAID 卷
- jquery - 如何在 Jquery datePicker 选项 beforeShowDay 中运行多个函数并返回
- asp.net - 如何在实体框架中映射一个点?
- python - 使用glom,如何连接可选字符串?
- aws-serverless - AWS 部署无服务器限制?
- asp.net-core-mvc - 向 Twilio 发送重定向 Uri 到同一控制器中的另一个操作
- css - 如何将伪类有效/无效与 Angular 表单控件验证器混合?
- influxdb - 在 influxdb 中显示具有相似名称的测量
- gcc - AVR-GCC Windows 与 Linux