android - 如何使用 SAF 从树 URI 路径访问目录及其文件

标签 android android-10.0 storage-access-framework android-storage android-11

我想选取目录中的所有文件,然后将这些文件的副本压缩版本存储在同一目录中。

如果我使用Intent.ACTION_OPEN_DOCUMENT_TREE,我会得到一棵树Uri,但我无法弄清楚如何获取其中包含的所有文件的文件Uri以及如何编写在目录本身中。

documentation我找不到任何类似的用例。

在强制 SAF 之前,获取目录路径并使用标准文件方法就足够了,不幸的是,现在所有过去基于文件和显式路径的方法都被这个 SAF 破坏了。

最佳答案

我花了一段时间才弄清楚:

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
private List<Uri> readFiles(Context context, Intent intent) {
    List<Uri> uriList = new ArrayList<>();

    // the uri returned by Intent.ACTION_OPEN_DOCUMENT_TREE
    Uri uriTree = intent.getData();
    // the uri from which we query the files
    Uri uriFolder = DocumentsContract.buildChildDocumentsUriUsingTree(uriTree, DocumentsContract.getTreeDocumentId(uriTree));

    Cursor cursor = null;
    try {
        // let's query the files
        cursor = context.getContentResolver().query(uriFolder,
                new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                // build the uri for the file
                Uri uriFile = DocumentsContract.buildDocumentUriUsingTree(uriTree, cursor.getString(0));
                //add to the list
                uriList.add(uriFile);

            } while (cursor.moveToNext());
        }

    } catch (Exception e) {
        // TODO: handle error
    } finally {
        if (cursor!=null) cursor.close();
    }

    //return the list
    return uriList;
}

关于android - 如何使用 SAF 从树 URI 路径访问目录及其文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62353325/

相关文章:

java - 如何在android 10中获取图像的方向信息?

Android SAF(存储访问框架): Get particular file Uri from TreeUri

android - Android 上最具扩展性的推送通知系统是什么?

android - 钛 android 中的 tableview 子项中的标签文本未更新。但在 IOS 中有效

android - 通过 Android 10 SDK 升级无法从后台应用访问剪贴板

android - Android Q 中的深色主题配置更改

android - 作为 "Private"(仅限本地)文件夹/文件选择器的存储访问框架?

android - 存储访问框架不更新 MediaScanner (MTP)

android - 在 native Android 应用程序中使用 WebView 整个布局有用吗?

android - 如何在 Android style.xml 文件中使用自定义父级?