android - 使用 FileProvider Android 从可移动 SD 卡打开文件时出错

标签 android pdf sd-card fileprovider

我的目标是从任何内存中打开 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>

问题:

当我尝试从设备内存中打开 pdf 文件时 (/storage/emulated/0/hts221.pdf) - 一切正常。

但是,当我尝试从 SD 卡打开 pdf 文件 (/storage/1317-231C/LPS22HB.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。现在这两个文件都工作正常。

关于android - 使用 FileProvider Android 从可移动 SD 卡打开文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64658588/

相关文章:

android - 在 Android 上将游戏 Assets 下载到 SD 卡

java - Android - Java空指针异常

c# - 使用 iTextSharp 获取复选框的导出值

html - 如何在 iframe 中查看 Google drive pdf 链接

javascript - 在 PDF 中使用 Javascript 列出 XFA 对象的属性

SD卡中的Android PhoneGap www文件夹

android - 服务什么时候会进入休眠状态?

android - 如何在特定时间触发android中的后台服务?

java - 在 android 中的 ListView 中显示详细信息的优雅方式

android - 如何在android中以编程方式隐藏sdcard中的文件夹