[英]How to get access to "/storage/emulated/0/Android/media/" using Storage Access Framework?
[英]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.