FileProvider

基础

官网链接

为了安全地共享本 app 的文件,您需要配置您的应用程序,以 Content URI 形式为文件提供安全的句柄。 FileProvider 会根据你在 XML 中提供的规范生成文件的 Content URI 。

  1. FileProvider 继承于 ContentProvider ,它只是内容提供者的一个特殊子类。

  2. 也可以不使用 FileProvider ,而自己定义一个 ContentProvider 。

几个方法的返回路径

方法名 返回路径
getExternalCacheDir() sd 卡中 Android/data/包名/cache 目录
getExternalFilesDir(String) sd 卡中 Android/data/包名/files/xx 目录,xx为方法参数
getCacheDir() 内部存储目录下的 cache 目录
getDir() 内部存储目录下的 app_xx 目录 ,其中 xx 为方法参数
getFilesDir() 内部存储目录下 files 目录

Manifest 配置

在清单文件中进行如下配置:

   <application
        ...>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.myapp.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>

<meta-data> 中 resource 属性指定了 xml 文件名,该文件位于 res/xml 文件夹下。
authorities 指定了 FileProvider 生成 URI 的authorities。

xml

在 res/xml 文件夹下建立以 resource 属性值为名的 xml 文件,在该文件中指定本 app 可以共享的文件目录,所有可以共享的目录只能在该 xml 中指定,无法通过代码动态完成

可以参考如下示例:

<paths>
    <files-path path="images/" name="url_name" />
</paths>
  1. path 属性指定了共享的子目录, name 属性指定了共享目录在 content URI 中的别名。子目录与别名是一一对应关系

  2. <paths> 中可以有多个子标签。

  3. 父目录名通过子标签名指定。如上面的 files-path 指定的父目录就是 getFilesDir() 返回的目录。

  4. 在上面例子中,如果共享的是 images 目录下的 default_image.jpg ,其对应的 content URI 如下:

content://com.example.myapp.fileprovider/url_name/default_image.jpg

其文件的真实路径

Context.getFilesDir() +"/images/default_image.jpg"

可以发现,转成 URI 后,images 目录下的路径会全部真实地保留。保留的部分叫剩余路径(为后期分析源码方便,自己取的名字)

子标签名

官网链接

标签名 对应的目录
files-path Context#getFilesDir()
cache-path Context#getCacheDir()
external-path Environment.getExternalStorageDirectory()
external-files-path Context#getExternalFilesDir
external-cache-path Context#getExternalCacheDir()

源码分析

因为是 ContentProvider ,所以先看其 attachInfo 方法。

attachInfo()

public void attachInfo(Context context, ProviderInfo info) {
        super.attachInfo(context, info);
        //对 exported 与 grantUriPermissions 属性值进行判断,其要求两者值必须分别为 false 与 true,否则就会扔异常。
        ……
        // authority 的值就是 authorities 属性的值
        mStrategy = getPathStrategy(context, info.authority);
    }

 private static PathStrategy getPathStrategy(Context context, String authority) {
        PathStrategy strat;
        synchronized (sCache) {
           //以 authority 值为 key 对 PathStrategy 对象进行缓存
            strat = sCache.get(authority);
            if (strat == null) {
                try {
                    strat = parsePathStrategy(context, authority);
                } 
                // 省略异常处理代码
                sCache.put(authority, strat);
            }
        }
        return strat;
    }

对 strat 进行初始化时,会调用 parsePathStrategy 方法,其主要就是解析在清单文件中指定的 xml 文件。

private static PathStrategy parsePathStrategy(Context context, String authority)
            throws IOException, XmlPullParserException {
        final SimplePathStrategy strat = new SimplePathStrategy(authority);
        //读取清单文件中配置的 xml 文件
        final ProviderInfo info = context.getPackageManager()
                .resolveContentProvider(authority, PackageManager.GET_META_DATA);
        final XmlResourceParser in = info.loadXmlMetaData(
                context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
        //对 in 进行非空判断 ,忽略。下面是对 in 进行 xml 解析
        int type;
        while ((type = in.next()) != END_DOCUMENT) {
            if (type == START_TAG) {
                final String tag = in.getName();
                //分别获取 name 属性与 path 属性
                final String name = in.getAttributeValue(null, ATTR_NAME);
                String path = in.getAttributeValue(null, ATTR_PATH);

                File target = null;
                if (TAG_ROOT_PATH.equals(tag)) {
                    target = DEVICE_ROOT;
                } else if (TAG_FILES_PATH.equals(tag)) {// 标签名为 files-path
                    target = context.getFilesDir();
                } else if (TAG_CACHE_PATH.equals(tag)) {// 标签名为 cache-path
                    target = context.getCacheDir();
                } else if (TAG_EXTERNAL.equals(tag)) {// 标签名为 external-path
                    target = Environment.getExternalStorageDirectory();
                } else if (TAG_EXTERNAL_FILES.equals(tag)) {// 标签名为 external-files-path
                    //这段代码的作用就是将 target 赋值为 getExternalFilesDir() 的返回值
                } else if (TAG_EXTERNAL_CACHE.equals(tag)) {// 标签名为 external-cache-path
                    //这段代码的作用就是将 target 赋值为 getExternalCacheDir() 的返回值
                }

                if (target != null) {
                    // buildPath 会在 target 目录下建立一个以 path 值为名的目录
                    strat.addRoot(name, buildPath(target, path));
                }
            }
        }

        return strat;
    }

    private static File buildPath(File base, String... segments) {
        File cur = base;
        for (String segment : segments) {
            if (segment != null) {
                cur = new File(cur, segment);
            }
        }
        return cur;
    }

其余方法

其他几个方法的实现,基本上都是通过 PathStrategy 完成的。如

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

PathStrategy 与 SimplePathStrategy

PathStrategy 的唯一子类是 SimplePathStrategy。它会在 parsePathStrategy() 中被创建。

  static class SimplePathStrategy implements PathStrategy {
        private final String mAuthority;
        //以 name 属性值为 key ,以标签名与 path 值联合指定的目录 File 为 value
        private final HashMap<String, File> mRoots = new HashMap<String, File>();

        public SimplePathStrategy(String authority) {
            mAuthority = authority;
        }

        // name 是 xml 中定义 name 属性值,而 root 是根据 xml 中标签名与 path 属性值联合指定的一个本地文件目录,name 与 root 是一一对应关系
        public void addRoot(String name, File root) {
            ……
            mRoots.put(name, root);
        }

        @Override
        public Uri getUriForFile(File file) {
            String path;// path 指代 file 的路径。
            
            Map.Entry<String, File> mostSpecific = null;
            for (Map.Entry<String, File> root : mRoots.entrySet()) {
                final String rootPath = root.getValue().getPath();

               // 查找最接近 file 路径的 Map.Entry<String, File> 对象。

                if (path.startsWith(rootPath) && (mostSpecific == null
                        || rootPath.length() > mostSpecific.getValue().getPath().length())) {
                    mostSpecific = root;
                }
            }

            // mostSpecific  非空判断,略
            
            // 以下对 path 进行处理,并最终转成 content://authority/name 形式的 URI
            // 通过该种方式处理,最终会将指定的文件根据清单文件中的 authority 以及 xml 中指定的 name 转换成 URI

            final String rootPath = mostSpecific.getValue().getPath();
            // 截取指定 file 的除 标签名及 path 属性指定的剩余部分
            if (rootPath.endsWith("/")) {
                path = path.substring(rootPath.length());
            } else {
                path = path.substring(rootPath.length() + 1);
            }
            // 将 path 转换成  name/剩余路径  形式
            path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
            return new Uri.Builder().scheme("content")
                    .authority(mAuthority).encodedPath(path).build();
        }

        @Override
        public File getFileForUri(Uri uri) {
            // 获取到的内容形式为:/name/剩余路径
            String path = uri.getEncodedPath();

            final int splitIndex = path.indexOf('/', 1);
            // xml 中指定的 name 属性值
            final String tag = Uri.decode(path.substring(1, splitIndex));
            // 文件的剩余路径
            path = Uri.decode(path.substring(splitIndex + 1));
            // 获取文件的根路径
            final File root = mRoots.get(tag);
            if (root == null) {
                throw new IllegalArgumentException("Unable to find configured root for " + uri);
            }

            File file = new File(root, path);
            try {
                file = file.getCanonicalFile();
            } catch (IOException e) {
                throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
            }

            if (!file.getPath().startsWith(root.getPath())) {
                throw new SecurityException("Resolved path jumped beyond configured root");
            }

            return file;
        }
    }

总结

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

推荐阅读更多精彩内容