繁体   English   中英

如何使用Android Storage Access Framework获取DocumentContract

[英]How to get a DocumentContract using Android Storage Access Framework

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

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

调出文件/文件夹选择器

复制:

   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;
}

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

无法从SAF获得URI权限,而无需调用另一个UI。

由于使用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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM