通过 Intent 选择文件然后删除 onActivityResult

Pick file via Intent then Delete onActivityResult

我想打开一个目录,然后我应该可以选择一个文件然后将其删除。这是我打开目录的代码:

public void openDirectory() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/drugdiy/doc");
        intent.setDataAndType(uri, "*/*");
        startActivityForResult(Intent.createChooser(intent, "Open folder"), 0);
    }

我不知道如何将 uri 传递给 onActivityResult 以便我可以删除它?

    public void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode) {
            case 0: {
                Uri uri = 
                File file = new File(uri.getPath());
                file.delete();
            }
        }
    }

首先,如果你阅读the documentation for ACTION_GET_CONTENT,你会看到:

Input: getType() is the desired MIME type to retrieve. Note that no URI is supplied in the intent, as there are no constraints on where the returned data originally comes from.

(强调)

因此,您的第一个代码片段将适用于少数设备。

其次,ACTION_GET_CONTENT不一定要return给你一个文件,更不用说你可以删除的文件了。

There are many file-picker libraries available for Android。使用一个。他们应该给你一个 File 回复,然后你可以在 File.

上调用 delete()