android - FileProvider 包括所有子文件夹

标签 android

我有一个运行良好的 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>

设置共享 Intent :

     File f = new File(_fileFullName);

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

     _shareProvider.SetShareIntent(intent);

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

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

Failed to find configured root that contains /storage/emulated/0/Android/data/app.namespace/files/subfolder/data.png on the GetUriForFile call.

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

最佳答案

请忽略,发现了我的问题。我使用 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;
                }
            }

关于android - FileProvider 包括所有子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26231520/

相关文章:

Android base64 编码的字符串无效?

android - 找不到 Firebase 文件异常

android - 为什么 MaterialButton 文本不包含完整空间?

android - 错误 : Your cpu does not support required features(vt-x or svm) on AMD CPU under Windows

android - 从 Fragment 调用 FragmentActivity

安卓工作室 : Getting error during build gradle

android - 从 ImageView 中捏和图像并获得它的特定部分?

android - react native 图像缓存 Android

php - 通过 Zend_Gdata 使用来自 android 的 AccountManager.getAuthToken 的结果(401 未经授权)

android - 我们可以在 Android 中使用 Hadoop 和任何 NoSQL 数据库来代替 SQLite