首页 > 解决方案 > 使用 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,但我认为在这种情况下这并不重要。

标签: androidpdfsd-cardfileprovider

解决方案


添加

 <root-path name="root" path="." />

到 xml/provider_path。现在这两个文件都可以正常工作。


推荐阅读