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