如何使用 Android 存储访问框架获取 DocumentContract

How to get a DocumentContract using Android Storage Access Framework

我正在尝试在我的应用程序中实施 SAF。我已经设法使用以下方法将音乐文件复制到外部 SD 卡:

         Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    startActivityForResult(intent, REQUEST_CODE_OPEN_DIRECTORY);

这会调出 File/folder 选择器

复制:

   private String copyFile(String inputPath, String inputFile, Uri treeUri) {
    InputStream in = null;
    OutputStream out = null;
    String error = null;
    DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);
    String extension = inputFile.substring(inputFile.lastIndexOf(".")+1,inputFile.length());

    try {
        DocumentFile newFile = pickedDir.createFile("audio/"+extension, inputFile);
        out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
        in = new FileInputStream(inputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        // write the output file (You have now copied the file)
        out.flush();
        out.close();

    } catch (FileNotFoundException fnfe1) {
        error = fnfe1.getMessage();
    } catch (Exception e) {
        error = e.getMessage();
    }
    return error;
}

但是 当用户选择 "move" 我想删除原始位置的文件,这些文件可能不在文档树中,因为它们与选择的文件夹无关。它们的路径取自 Mediastore_DATA 字段。 问题是如何获得包含这些文件的 DocumentContract 以便删除它们?

无法从 SAF w/o 调用另一个 UI.

获得 URI 许可

由于您使用 MediaStore 获取媒体文件,您可以使用 ContentResolver.delete() 和您必须删除它的媒体 URI。我假设您有 WRITE_EXTERNAL_STORAGE 许可。我不建议使用 File 直接删除底层文件,因为 MediaStore 没有机会清理它。

或者,您也可以尝试https://developer.android.com/reference/android/os/storage/StorageVolume.html#createAccessIntent(java.lang.String) 获取对整个主存储的树 URI 权限。但是它只适用于 API 24.