FileProvider源码浅析与节点配置

大家都知道安卓7.0应用共享文件的行为变更
对于面向 Android 7.0 的应用,Android 框架执行的 StrictMode API 政策禁止在您的应用外部公开 file:// URI。如果一项包含文件 URI 的 intent 离开您的应用,则应用出现故障,并出现 FileUriExposedException 异常。
要在应用间共享文件,您应发送一项 content:// URI,并授予 URI 临时访问权限。进行此授权的最简单方式是使用FileProvider类。
首先在manifest里面注册provider。在之前的使用过程中有一点我一直是一知半解。就是配置节点文件
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/app_file_paths" />
其中app_file_paths这些节点与FileProvider到底有什么关系呢?
我们回到问题的原点FileProvider获取URI,FileProvider通过getUriForFile方法获取。我们点入进去看一下里面的实现

public static Uri getUriForFile(@NonNull Context context, @NonNull String authority, @NonNull File file) {
        FileProvider.PathStrategy strategy = getPathStrategy(context, authority);
        return strategy.getUriForFile(file);
 }
private static FileProvider.PathStrategy getPathStrategy(Context context, String authority) {
        HashMap var3 = sCache;
        synchronized(sCache) {
            FileProvider.PathStrategy strat = (FileProvider.PathStrategy)sCache.get(authority);
            if (strat == null) {
                try {
                    strat = parsePathStrategy(context, authority);
                } catch (IOException var6) {
                    throw new IllegalArgumentException("Failed to parse android.support.FILE_PROVIDER_PATHS meta-data", var6);
                } catch (XmlPullParserException var7) {
                    throw new IllegalArgumentException("Failed to parse android.support.FILE_PROVIDER_PATHS meta-data", var7);
                }

                sCache.put(authority, strat);
            }

            return strat;
        }
 }

关键代码parsePathStrategy(context, authority);

private static FileProvider.PathStrategy parsePathStrategy(Context context, String authority) throws IOException, XmlPullParserException {
        FileProvider.SimplePathStrategy strat = new FileProvider.SimplePathStrategy(authority);
        ProviderInfo info = context.getPackageManager().resolveContentProvider(authority, 128);
        XmlResourceParser in = info.loadXmlMetaData(context.getPackageManager(), "android.support.FILE_PROVIDER_PATHS");
        if (in == null) {
            throw new IllegalArgumentException("Missing android.support.FILE_PROVIDER_PATHS meta-data");
        } else {
            int type;
            while((type = in.next()) != 1) {
                if (type == 2) {
                    String tag = in.getName();
                    String name = in.getAttributeValue((String)null, "name");
                    String path = in.getAttributeValue((String)null, "path");
                    File target = null;
                    if ("root-path".equals(tag)) {
                        target = DEVICE_ROOT;
                    } else if ("files-path".equals(tag)) {
                        target = context.getFilesDir();
                    } else if ("cache-path".equals(tag)) {
                        target = context.getCacheDir();
                    } else if ("external-path".equals(tag)) {
                        target = Environment.getExternalStorageDirectory();
                    } else {
                        File[] externalMediaDirs;
                        if ("external-files-path".equals(tag)) {
                            externalMediaDirs = ContextCompat.getExternalFilesDirs(context, (String)null);
                            if (externalMediaDirs.length > 0) {
                                target = externalMediaDirs[0];
                            }
                        } else if ("external-cache-path".equals(tag)) {
                            externalMediaDirs = ContextCompat.getExternalCacheDirs(context);
                            if (externalMediaDirs.length > 0) {
                                target = externalMediaDirs[0];
                            }
                        } else if (VERSION.SDK_INT >= 21 && "external-media-path".equals(tag)) {
                            externalMediaDirs = context.getExternalMediaDirs();
                            if (externalMediaDirs.length > 0) {
                                target = externalMediaDirs[0];
                            }
                        }
                    }

                    if (target != null) {
                        strat.addRoot(name, buildPath(target, path));
                    }
                }
            }

            return strat;
        }
}

可以看到上段代码就是解析xml文件也就是我们的app_file_paths
然后添加到root里面。sCache就是保存了我们注册的provider的一个Map集合,它采用authority作为key。最终返回一个FileProvider.PathStrategy对象这是一个接口我们可以看到里面有两个方法

interface PathStrategy {
        Uri getUriForFile(File var1);

        File getFileForUri(Uri var1);
}

SimplePathStrategy实现了该接口。我们看看SimplePathStrategy的getUriForFile

        @Override
        public Uri getUriForFile(File file) {
            String path;
            try {
                path = file.getCanonicalPath();
            } catch (IOException e) {
                throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
            }

            // Find the most-specific root path
            Map.Entry<String, File> mostSpecific = null;
            for (Map.Entry<String, File> root : mRoots.entrySet()) {
                final String rootPath = root.getValue().getPath();
                if (path.startsWith(rootPath) && (mostSpecific == null
                        || rootPath.length() > mostSpecific.getValue().getPath().length())) {
                    mostSpecific = root;
                }
            }

            if (mostSpecific == null) {
                throw new IllegalArgumentException(
                        "Failed to find configured root that contains " + path);
            }

            // Start at first char of path under root
            final String rootPath = mostSpecific.getValue().getPath();
            if (rootPath.endsWith("/")) {
                path = path.substring(rootPath.length());
            } else {
                path = path.substring(rootPath.length() + 1);
            }

            // Encode the tag and path separately
            path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
            return new Uri.Builder().scheme("content")
                    .authority(mAuthority).encodedPath(path).build();
        }

path是文件的路径,mRoots是一个保存xml中节点的集合他是在parsePathStrategy()中的调用addRoot添加的
可以看到显示遍历mRoots最终找到一个与path路径最匹配的节点。这里插一下xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external" path="."/><!--Environment.getExternalStorageDirectory-->
    <!--下面这两个感觉不是很必要-->
    <!--<external-files-path name="externalfile" path="."/>--><!--Context.getExternalFileDir-->
    <!--<external-cache-path name="externalcache" path="."/>--> <!--Context.getExternalFileDir-->
    <cache-path name="cache" path="."/><!--Context.getCacheDir-->
    <!--<files-path name="files" path="."/>--> <!--Context.getFilesDir()-->
    <!--<root-path name="root" path="" />--> <!--new File("/")系统的根目录-->
</paths>

external-path是包含external-files-path和external-cache-path的我们直接取external-path这样可以减少mRoot的匹配次数
所以建议少配置节点且把建议external-path的path设置为“.”也就是包括该目录下的全部路径
接下回到上面的代码中。在找到了最匹配的mostSpecific之后采用xml节点中name来代替mostSpecific这一部分。采用content作为schme这其实就是把file://包装成content。
值得一提的是如果配置的path越详细那么隐藏的路径内容也越多,安全性更高。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354

推荐阅读更多精彩内容