Android Fileprovider:IllegalArgumentException:无法找到包含的已配置根目录

use*_*120 15 pdf authority android-fileprovider

我有一个关于android FileProvider的问题.我想保存一个pdf文档并使用默认程序打开它.我不想将它保存在外部存储中.

在我成功将pdf保存到FilesDirectory/export/temp.pdf之后,
我尝试使用FileProvider.getUriForFile()生成URI.

File path = new File(getFilesDir(), "export");
File pdf = new File(path + File.separator + "temp.pdf");
pdf.getParentFile().mkdirs();

if (!pdf.exists())
    pdf.createNewFile();

Uri uri = FileProvider.getUriForFile(getApplicationContext(), "?", pdf);
Run Code Online (Sandbox Code Playgroud)

问题:我必须传递什么作为第二个参数"权限" - 我的文件的位置,可以授予URI权限的类或其他什么?无论我尝试过什么导致IllegalArgumentException或NullPointerException.我的FileProvider(XML):

<provider         
    android:name="android.support.v4.content.FileProvider"           
        android:authorities="com.example.myApp.myActivity"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data                 
             android:name="android.support.FILE_PROVIDER_PATHS"                           
             android:resource="@xml/file_path"/>                                       
</provider>
Run Code Online (Sandbox Code Playgroud)

引用文件:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="pdfTemplates" path="export/" />
</paths>
Run Code Online (Sandbox Code Playgroud)

use*_*120 11

我懂了.有两个不同的问题

  1. 第一期由CodeDiving回答.我不得不从getUriForFile调用的provider-declaration中使用Authority.使用其他类导致NullPointerException.

  2. 我试图从filesDirectory获取一个文件,但在我的file_path中,我只声明了一个缓存Directory的路径.我将其更改为'files-path'并且它有效.此错误导致IllegalArgumentException.

  • 确保它是`files-path`而不是`file-path`.很容易错过! (2认同)
  • 这个`files-path`在哪里?我的意思是你在哪里指定它. (2认同)
  • @IgorGanapolsky他用引用的xml文件_file_path_中的`<files-path`替换了`<cache-path`. (2认同)

小智 8

根据您的FileProvider文件(XML),第二个参数是com.example.myApp.myActivity.那是

Uri uri = FileProvider.getUriForFile(getApplicationContext(),
                                     "com.example.myApp.myActivity", pdf);
Run Code Online (Sandbox Code Playgroud)