FileProvider使用

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

 

  1. <paths xmlns:android="http://schemas.android.com/apk/res/android">
  2. <files-path name="my_images" path="images/"/>
  3. </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文件

 

  1. <paths xmlns:android="http://schemas.android.com/apk/res/android">
  2. <files-path name="my_images" path="images/"/>
  3. <files-path name="my_docs" path="docs/"/>
  4. </paths>

2.配置AndroidManifest.xml

*** android:authorities在FileProvider中使用

 

  1. <provider
  2. android:name="android.support.v4.content.FileProvider"
  3. android:authorities="com.mydomain.fileprovider"
  4. android:exported="false"
  5. android:grantUriPermissions="true">
  6. <meta-data
  7. android:name="android.support.FILE_PROVIDER_PATHS"
  8. android:resource="@xml/file_paths" />
  9. </provider>

3.使用FileProvider

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

 

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

4.自定义FileProvider

 

  1. class MyFileProvider extends FileProvider {}
  2. AndroidMenifest.xml中配置
android:name
android:authorities即可
posted @ 2018-10-12 16:13  土金  阅读(2063)  评论(0编辑  收藏  举报