我对Android编程相对较新,跟随了几个不同的教程。目标是将pdf文件从assets文件夹复制到外部存储器,然后在按下按钮以打开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);
我按照上述链接中的说明设置了我的文件提供者。
<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()
为真时构建意图。添加那段代码。 - greenapps