FileProvider使用

理解FileProvider与ContentURI
本文详细解析了Android中FileProvider的使用方法,包括如何通过XML配置文件指定内存区域和路径,以及如何在AndroidManifest.xml中配置authorities。此外,还介绍了如何生成contentURI,并提供了自定义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即可

转载于:https://www.cnblogs.com/zhongle/p/9778756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值