[英]How to get a DocumentContract using Android Storage Access Framework
I am trying to implement the SAF in my app. 我正在尝试在我的应用中实施SAF。 I have managed to copy music files to the external sdcard using the following: 我设法使用以下方法将音乐文件复制到外部sdcard:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_CODE_OPEN_DIRECTORY);
which brings up the File/folder Picker 调出文件/文件夹选择器
to copy: 复制:
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;
}
BUT when user selected "move" I want to delete the files in the original location(s) which may not be in the documenttree as they have nothing to do with what folder was picked. 但是,当用户选择“移动”时,我想删除原始位置的文件,这些位置可能不在文档树中,因为它们与选择的文件夹无关。 Their paths are taken from the Mediastore_DATA field. 它们的路径来自Mediastore_DATA字段。 Question is how can I get a DocumentContract with those files so that I can delete them? 问题是如何获得带有这些文件的DocumentContract,以便删除它们?
There is no way to obtain URI permission from SAF w/o invoking another UI. 无法从SAF获得URI权限,而无需调用另一个UI。
Since you use MediaStore to obtain media file, you can use ContentResolver.delete() with the Media URI you have to delete it. 由于使用MediaStore获取媒体文件,因此可以将ContentResolver.delete()与必须删除的媒体URI一起使用。 I assume you have WRITE_EXTERNAL_STORAGE permission. 我假设您具有WRITE_EXTERNAL_STORAGE权限。 I don't recommend using File to delete the underlying file directly as MediaStore won't have a chance to clean it up. 我不建议使用File直接删除基础文件,因为MediaStore将没有机会对其进行清理。
Alternatively, you can also try https://developer.android.com/reference/android/os/storage/StorageVolume.html#createAccessIntent(java.lang.String) to obtain tree URI permission to the entire primary storage. 另外,您也可以尝试https://developer.android.com/reference/android/os/storage/StorageVolume.html#createAccessIntent(java.lang.String)获得对整个主存储的树URI权限。 However it only works from API 24. 但是,它仅适用于API 24。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.