FileProvider小记

官方地址:FileProvider
FileProviderContentProvider的特殊子类,可以安全的分享文件通过创建content:// Uri来替代file:/// Uri

使用步骤

This overview of FileProvider includes the following topics:

  1. manifest配置FileProvider
  2. 指定paths路径
  3. 通过FileProvider给文件创建URI
  4. 对URI临时授权
  5. 将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);

猜你喜欢

转载自blog.csdn.net/momo_ibeike/article/details/79501100
今日推荐