Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/198.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android FileProvider找不到文件_Android_Android Fileprovider - Fatal编程技术网

Android FileProvider找不到文件

Android FileProvider找不到文件,android,android-fileprovider,Android,Android Fileprovider,我对Android编程比较陌生,并学习了一些不同的教程。 目标是将pdf文件从assets文件夹复制到外部存储器,然后在按下按钮打开pdf查看器时打开一个Intent。我尝试使用FileProvider将代码调整为最新的Android版本,如下所述: 在较旧的Android版本上打开文件是有效的,这样我就知道整个复制过程都在工作,问题是我无法找出代码中的错误在哪里 File file = new File(Environment.getExternalStorageDirectory() +

我对Android编程比较陌生,并学习了一些不同的教程。 目标是将pdf文件从assets文件夹复制到外部存储器,然后在按下按钮打开pdf查看器时打开一个Intent。我尝试使用FileProvider将代码调整为最新的Android版本,如下所述:

在较旧的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>


如果有人能解释我的错误,我会非常高兴。

来自评论:我必须添加intent.addFlags(intent.FLAG\u GRANT\u READ\u URI\u PERMISSION);另外。

您得到的确切错误是什么?在你的应用程序中?还是在用户选择的应用程序中?不清楚。您应该只构建意图为
的文件。exists()
为true。从注释中添加代码:我必须添加intent.addFlags(intent.FLAG\u GRANT\u READ\u URI\u PERMISSION);另外,这个问题通过添加标志解决了,谢谢。我花了一段时间,因为我在Kotlin使用了
而不是
添加了这个标志!