Android FileProvider 找不到文件
Android FileProvider cannot find file
我是 Android 编程的新手,学习过几个不同的教程。
目标是将 pdf 文件从资产文件夹复制到外部存储,然后在按下按钮打开 PDF 查看器时打开 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 link。
<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>
如果有人能解释我的错误,我将非常高兴。
来自评论:我必须添加 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);还有。
我是 Android 编程的新手,学习过几个不同的教程。 目标是将 pdf 文件从资产文件夹复制到外部存储,然后在按下按钮打开 PDF 查看器时打开 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 link。
<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>
如果有人能解释我的错误,我将非常高兴。
来自评论:我必须添加 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);还有。