[英]Error while opening file from removable SD-Card with FileProvider Android
我的目標是從任何內存中打開 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。 現在這兩個文件都可以正常工作。
FileProvider 無法提供來自可移動微型 SD 卡的文件。
如果您想從可移動 micro SD 卡提供文件,請擴展 ContentProvider 來執行此操作。
很難相信 root-path 會解決這個問題,但我會盡快檢查。
更新:確實有效。 在 android 11 上,Android/data 保持關閉狀態。
很棒的發現! (我想我以前看過但忘記了。嗯……所有的問題和答案都是重復的,你知道的。)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.