安卓文件提供者无法找到文件

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

我很希望有人能解释我的错误。

你具体遇到了什么错误?是在你的应用程序中还是在用户选择的应用程序中?不太清楚。 - greenapps
你应该只在 file.exists() 为真时构建意图。添加那段代码。 - greenapps
1
从注释中:我还必须添加intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);。 - greenapps
问题已经通过添加标志解决,非常感谢。 - Kevin Sabanagic
1个回答

13

从评论中得知:我还需要添加intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);


我花了一些时间,因为在 Kotlin 中,我使用 and 而不是 or 添加了此标志! - AlexAndro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接