Android 一起来看看 7.0 的新特性 FileProvider

在Android7.0中为了提高私有文件的安全性,面向 Android N 或更高版本的应用私有目录将被限制访问。
对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在应用外部公开 file:// URI , 如果一项包含文件 URI 的 intent 离开应用,则应用出现故障,并出现 FileUriExposedException 异常。

要应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用 FileProvider 类。如需了解有关权限和共享文件的详细信息,请参阅 共享文件

FileProvider 实际上是 ContentProvider 的一个子类,它的作用也比较明显,file://Uri 不给用,那么换个 Uri 为 content:// 来替代。

Provider 使用详解

1.定义 FileProvider

我们先在 AndroidManifest 中进行注册:

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.qgchat.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
        </provider>

从上面也可以看出 FileProvider 是 ContentProvider 的子类。
注册时其他属性都是固定的,只有android:authorities这个属性是自定义的,一般是你项目的包名加fileprovider。

2、指定可分享的文件路径

FileProvider 只能为指定的目录中的文件生成内容 URI。要指定目录,就必须使用 < paths > 元素的子元素在 XML 中指定其存储区域和路径。
我们在res文件夹下创建一个名为xml的目录,并在其中创建一个filepaths.xml 的新文件。
在 filepaths.xml 文件中,便可以指定文件存储的区域和路径。例如,以下路径元素告诉 FileProvider,你打算为私有文件区域的 images/ 子目录 请求内容 URI:

<paths>
    <external-path
        name="my_images"
        path="Pictures"/>
</paths>

< paths > 必须包含以下元素中一个或者多个子元素

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <root-path name="root" path="" />
    <files-path name="files" path="" />
    <cache-path name="cache" path="" />
    <external-path name="external" path="" />
    <external-files-path name="name" path="path" />
     <external-cache-path name="name" path="path" />
</paths>
  • < root-path/> 代表设备的根目录new File(“/”);
  • < files-path/> 代表context.getFilesDir()
  • < cache-path/> 代表context.getCacheDir()
  • < external-path/> 代表Environment.getExternalStorageDirectory()
  • < external-files-path>代表context.getExternalFilesDirs()
  • < external-cache-path>代表getExternalCacheDirs()

每个节点都使用两个属性:
name
path

path 即为代表目录下的子目录,例如:
< external-path name=”external” path=”pics”/>

代表的目录即为:Environment.getExternalStorageDirectory()/pics

当这么声明以后,代码可以使用你所声明的当前文件夹以及其子文件夹

这里你可能会有疑问,为什么要写这么个xml文件,有啥用呀?
刚才我们说了,现在要使用content://uri替代file://uri,那么,content://的uri如何定义呢?总不能使用文件路径吧,那不是骗自己么~

所以,需要一个虚拟的路径对文件路径进行映射,所以需要编写个xml文件,通过path以及xml节点确定可访问的目录,通过name属性来映射真实的文件路径。

写好 filepaths.xml 文件之后,要将此文件链接到 FileProvider 中,就必须添加一个 元素作为定义 FileProvider 的 元素的子元素。将 元素的 android : name 属性设置为 android.support.FILE_PROVIDER_PATHS, 将元素的 “android : resource” 属性设置为 @xml / filepaths (注意不要指定 .xml 拓展名)。例如:

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.qgchat.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

配置工作已经全部完成了,后面就需要将之前传递的 file:// 替换成 FileProvoider 需要用到的 content://,这就需要用到 FileProvider.getUriForFile() 方法了。

 public static Uri getUriForFile(Context context, String authority, File file) {
        final PathStrategy strategy = getPathStrategy(context, authority);
        return strategy.getUriForFile(file);
    }

从源代码中可以看到getUriForFile()需要传入 三个参数,第一个是上下文这个不必说,第二个是我们前面在 AndroidManifest.xml 文件中配置的 android:authorities 参数,第三个参数就是你需要共享的文件。调用这个方法会自动得到一个 file:// 转换成 content:// 的一个 Uri 对象,可以供我们直接使用,例如:

 Uri fileUri = FileProvider.getUriForFile(this, "com.example.qgchat.fileprovider", file);

4、给 Uri 授予临时权限

在7.0的系统上我们直接就可以使用了,但是在低版本的系统上,仅仅是把这个当成一个普通的Provider在使用,所以当我们生成一个 content:// 的 Uri 对象之后,其实还无法对其直接使用,还需要对这个 Uri 接收的 App 赋予对应的权限才可以。
这个授权的动作,提供了两种方式来授权:
通过 Context 的 grantUriPermission() 方法授权
Context 提供了两个方法

  • grantUriPermission(String toPackage, Uri uri, int modeFlags)
  • revokeUriPermission(Uri uri, int modeFlags);

可以看到grantUriPermission需要传递一个包名,就是你给哪个应用授权,但是很多时候,比如分享,我们并不知道最终用户会选择哪个app,所以我们可以这样:

List<ResolveInfo> resInfoList = context.getPackageManager()
            .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
    String packageName = resolveInfo.activityInfo.packageName;
    context.grantUriPermission(packageName, uri, flag);
}

根据 Intent 查询出所有符合的应用,都给他们授权,然后在不需要的时候通过 revokeUriPermission 移除权限。

配合 Intent.addFlags() 授权
既然这是一个 Intent 的 Flag,Intent 也提供了另外一种比较方便的授权方式,那就是使用 Intent.setFlags() 或者 Intent.addFlag 的方式
使用这种形式的授权,权限截止于该 App 所处的堆栈被销毁。也就是说,一旦授权,知道该 App 被完全退出,这段时间内,该 App 享有对此 Uri 指向的文件的对应权限,我们无法主动收回该权限了。

这两种方法相比较而言方法二更加简单,但是方法二容易出现不稳定性因素,大家还是不要偷懒使用方法一吧。

参考:
http://blog.csdn.net/lmj623565791/article/details/72859156

https://mp.weixin.qq.com/s/05EIPgg_4LjrRQxPjqG-gg

http://www.jianshu.com/p/56b9fb319310

发布了65 篇原创文章 · 获赞 24 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/shanshui911587154/article/details/78025061