FileProvider使用

版权声明:本文为博主原创文章,转载需注明博主文章链接。 https://blog.csdn.net/black_bread/article/details/69258613

*** FileProvider只能为你指定的目录下files生成content URI。通过属性paths,在xml文件中指定它的内存区域和路径。例如,下面的paths告诉FileProvider,打算为你的私有文件images/子目录请求content URIs。至少一个请求子元素。

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
</paths>
*** name和path

name:uri路径片段。为了执行安全,这个值隐藏你所共享的子目录名。此值的子目录名包含在路径属性中。

path:你所共享的子目录。虽然name属性是一个URI路径片段,但是path是一个真实的子目录名。注意,path是一个子目录,而不是单个文件或者多个文件。


1.files-path

<files-path name="name" path="path" />
代表与Context.getFileDir()相同的文件路径

2.cache-path

<cache-path name="name" path="path" />
代表与getCacheDir()相同的文件路径

3.external-path

<external-path name="name" path="path" />
代表与Environment.getExternalStorageDirectory()相同的文件路径

4.external-files-path

<external-files-path name="name" path="path" />
代表与Context#getExternalFilesDir(String) 和Context.getExternalFilesDir(null)相同的文件路径

5.external-cache-path

<external-cache-path name="name" path="path" />
代表与Context.getExternalCacheDir()相同的文件路径


使用:

1.新建res/xml/file_paths.xml文件

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="my_images" path="images/"/>
    <files-path name="my_docs" path="docs/"/>
</paths>
2.配置AndroidManifest.xml

*** android:authorities在FileProvider中使用

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.mydomain.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

3.使用FileProvider

*** 返回URI:content://com.mydomain.fileprovider/my_images/default_image.jpg.

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

4.自定义FileProvider


class MyFileProvider extends FileProvider {}
AndroidMenifest.xml中配置
android:name
android:authorities即可

猜你喜欢

转载自blog.csdn.net/black_bread/article/details/69258613