【问题标题】:FileProvider include all subfoldersFileProvider 包括所有子文件夹
【发布时间】:2014-10-07 20:21:50
【问题描述】:

我的 FileProvider 工作得非常好,我可以将文件共享给任何应用程序,这是我的代码:

文件路径.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
   <!-- choose between cache-path (cache storage), files-path (app-private storage) and  external-path (external storage) -->
   <cache-path path="/" name="strips" />
</paths>

设置分享意图:

     File f = new File(_fileFullName);

     var contentUri = FileProvider.GetUriForFile(this,
        G.FileProviderAuthorityName,
        f);
     intent.PutExtra(Intent.ExtraStream, contentUri);

     _shareProvider.SetShareIntent(intent);

这非常有效。我忘了在这里提到我的文件通常在应用程序缓存目录的子文件夹中,无论它们在哪里(文件夹是动态创建的),它都可以工作。

但是,当我将 xml 从缓存路径更改为文件路径(AppPrivate 存储)时,我得到 IllegalArgumentException:

未能找到配置的根目录包含 /storage/emulated/0/Android/data/app.namespace/files/subfolder/data.png 在 GetUriForFile 调用上。

我已经尝试了 FilePaths.xml 中的所有变体,用谷歌搜索了所有我能找到的答案。

【问题讨论】:

    标签: android


    【解决方案1】:

    请忽略,发现我的问题。我使用 getExternalFilesDir(null) 而不是 getFilesDir() 来保存我的文件。

    通过阅读 android 支持库源代码解决了这个问题。在内部 getUriForFile 执行此代码来决定使用哪个目录:

     File target = null;
                    if (TAG_ROOT_PATH.equals(tag)) {
                        target = buildPath(DEVICE_ROOT, path);
                    } else if (TAG_FILES_PATH.equals(tag)) {
                        target = buildPath(context.getFilesDir(), path);
                    } else if (TAG_CACHE_PATH.equals(tag)) {
                        target = buildPath(context.getCacheDir(), path);
                    } else if (TAG_EXTERNAL.equals(tag)) {
                        target = buildPath(Environment.getExternalStorageDirectory(), path);
                    }
    

    从 XML 定义中选择最接近的匹配路径,这意味着子文件夹不会有问题:

    // 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;
                    }
                }
    

    【讨论】:

    • 刚刚落入同一个陷阱。您可能为我节省了一个小时的调试时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2017-07-05
    • 2011-01-17
    相关资源
    最近更新 更多