【发布时间】:2017-08-27 08:08:50
【问题描述】:
我对 Android 编程比较陌生,并且学习了几个不同的教程。 目标是将 pdf 文件从 assets 文件夹复制到外部存储,然后在按下按钮打开 PDF-Viewer 时打开 Intent。我尝试使用 FileProvider 将我的代码调整为最新的 Android 版本,如下所述:https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en
在较旧的 Android 版本上打开文件有效,所以我知道整个复制过程都在工作,问题是我无法弄清楚我的代码中的错误在哪里。
File file = new File(Environment.getExternalStorageDirectory() + "/" + "index.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
//old version
Uri fileURI = Uri.fromFile(file);
//new version
Uri fileUri = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", file);
getApplicationContext().grantUriPermission(PACKAGE_NAME, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(fileUri,"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
我按照上面链接中的说明设置了我的 FileProvider。
<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
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
如果有人能解释我的错误,我会非常高兴。
【问题讨论】:
-
你到底得到了什么错误?在您的应用程序中?还是在用户选择的应用程序中?不清楚。
-
你应该只建立意图是
file.exists()是真的。添加该代码。 -
来自 cmets:我必须添加 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);也。
-
添加flag解决了这个问题,非常感谢
标签: android android-fileprovider