其他分享
首页 > 其他分享> > Android FileProvider无法找到文件

Android FileProvider无法找到文件

作者:互联网

我对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>

如果有人能解释我的错误,我会很高兴.

解决方法:

从评论:我不得不添加intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);也.

标签:android,android-fileprovider
来源: https://codeday.me/bug/20190722/1501526.html