当我启动 intent ACTION_OPEN_DOCUMENT_TREE 时,它会自动打开空的最近文件夹吗?

When i start the intent ACTION_OPEN_DOCUMENT_TREE it automatically opens empty recent folder?

我想要实现的是删除 sd 卡上的文件,我尝试了 file.delete 方法但没有用,因为 sd 卡现在是只读的。

所以我阅读了 post 关于 SAF(存储访问框架)的文章,通过存储我们在 onActivityResult 中获得的 treeUri 来获得 sd 卡写入权限。

文件删除现在工作正常,但是当我启动意图时 Intent.ACTION_OPEN_DOCUMENT_TREE 有时它 returns 最近的文件夹是空的以及显示方式sdcard 上的文件是单击溢出图标,然后 select 显示 SDCARD 或 Internal Storage 这可能会使某些人在 运行 我的应用程序时感到困惑。

我尝试将这些添加到我的意图中:intent.putExtra("android.content.extra.SHOW_ADVANCED", true); intent.putExtra("android.content.extra.FANCY", 真); intent.putExtra("android.content.extra.SHOW_FILESIZE", 真);

它在某些设备上有效,但它是私有的 API,在某些设备上它不起作用。

那么有没有办法自动打开特定目录或显示提示对话框,其中包含解释他们应该选择哪个目录的步骤?

private void getSDCardAccess(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
    startActivityForResult(intent, REQUEST_EXTERNAL_ACCESS);
} 


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_EXTERNAL_ACCESS && resultCode == RESULT_OK) {
        Uri treeUri = null;

        if (data != null){
            treeUri = data.getData();
        }

        if (treeUri != null && getActivity() != null) {
            getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION |
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            StorageUtil storageUtil = new StorageUtil(getActivity());
            //Takes the access so that we can use it again after the app reopens
            storageUtil.storeTreeUri(treeUri.toString());
            Log.d(TAG, "treeUri: " + treeUri.toString());
        }else{
            Log.d(TAG,"uri is empty!");
        }
    }
} 

is there a way to like automatically open a specific directory

如果您之前从 ACTION_OPEN_DOCUMENT_TREE 获得了 Uri,您应该能够通过 DocumentsContract.EXTRA_INITIAL_URI 提供它。每 the ACTION_OPEN_DOCUMENT_TREE documentation:

Callers can set a document URI through DocumentsContract.EXTRA_INITIAL_URI to indicate the initial location of documents navigator. System will do its best to launch the navigator in the specified document if it's a folder, or the folder that contains the specified document if not.


or show a hint dialog with steps explaining which directory they should chose?

在为 ACTION_OPEN_DOCUMENT_TREE 请求调用 startActivityForResult() 之前,您需要自己执行此操作。