如何使用存储访问框架在 SD 卡中创建新文件夹?

How to create new folder in sd card by using Storage Access Framework?

我想知道如何使用"Storage Access Framework"在SD卡上新建文件夹。如果你给我代码,那将是非常好的。 我已经搜索了其他问题和答案,但没有找到方法。

根据 "CommonsWare" 答案添加一些已经有效的代码。 请注意,这是我发现它可以在我的 phone SS A5 上使用 Android OS 5.1.1

在 SD 卡中创建新文件夹的唯一方法
    public void newFolder(View view)
    {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, NEW_FOLDER_REQUEST_CODE);
    }

    private static final int NEW_FOLDER_REQUEST_CODE = 43;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        super.onActivityResult(requestCode, resultCode, resultData);

        Uri currentUri = null;

        if (resultCode == Activity.RESULT_OK)
        {
            if (requestCode == NEW_FOLDER_REQUEST_CODE)
            {
                if (resultData != null) {
                    currentUri = resultData.getData();
                    DocumentFile pickedDir = DocumentFile.fromTreeUri(this, currentUri);
                    DocumentFile newDir = pickedDir.createDirectory("MyFolder");
                    textView.setText(newDir.getName());
                }
            }
        }
    }

您无法创建“在 SD 卡上创建新文件夹”。您可以在用户选择的其他文件夹中创建一个新文件夹,但不能强制用户选择可移动存储。

要在其他文件夹中创建一个新文件夹,这应该可行:

  1. an ACTION_OPEN_DOCUMENT_TREE Intent 上使用 startActivityForResult() 启动 activity,以允许用户选择文件夹。 包括 FLAG_DIR_SUPPORTS_CREATE 以确保您可以在文件夹中创建新内容。

  2. onActivityResult()中,将得到的Uri包裹在DocumentFile中,然后在call createDirectory()上创建一个新文件夹作为child 用户选择的内容。