官方地址:FileProvider
FileProvider
是ContentProvider
的特殊子类,可以安全的分享文件通过创建content:// Uri
来替代file:/// Uri
。
使用步骤
This overview of FileProvider includes the following topics:
- manifest配置FileProvider
- 指定paths路径
- 通过FileProvider给文件创建URI
- 对URI临时授权
- 将URI分享给其他app
一、manifest配置FileProvider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.momo.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
二、创建指定的file_paths文件
创建layout->xml->file_paths.xml
文件
<?xml version="1.0" encoding="utf-8"?>
<paths >
<files-path name="my_images" path="images/"/>
<files-path name="my_docs" path="docs/"/>
</paths>
<files-path name="name" path="path" />
files-path
代表Context.getFilesDir()
目录,path
指定子目录,name
负责起个别名。
同理:
cache-path 代表 Context.getCacheDir()目录
external-path 代表 Environment.getExternalStorageDirectory()目录
external-files-path 代表 Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)目录
external-cache-path 代表 Context.getExternalCacheDir()目录
external-media-path 代表 Context.getExternalMediaDirs()目录
三、指定文件创建URI
File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "com.momo.fileprovider", newFile);
四、临时授权
//指定授权包名和具体权限
grantUriPermission(BuildConfig.APPLICATION_ID, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intent = new Intent(this, SecondActivity.class);
intent.setData(contentUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);