用文档uri删除文件的方法
private void getDocumentUri(Uri mediaUri){
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && getActivity() != null) {
Uri documentUri = MediaStore.getDocumentUri(getActivity(), mediaUri);
if (documentUri != null) {
Log.d(TAG,"getDocumentUri: "+documentUri);
DocumentFile documentFile = DocumentFile.fromSingleUri(getActivity(), documentUri);
if (documentFile != null) {
Log.d(TAG, "getDocumentUri documentFile not null: " + documentFile);
if (documentFile.delete()) {
Log.i(TAG, "getDocumentUri Delete successful");
} else {
Log.i(TAG, "getDocumentUri Delete unsuccessful");
}
}
}
}
}catch(Exception e){
Log.e(TAG,"getDocumentUri error: " + e);
}
}Logcat错误
SecurityException: The app is not given any access to the document under path /storage/emulated/0/test/song.mp3 with permissions granted in [UriPermission {uri=content://com.android.externalstorage.documents/tree/primary%3AMusic, modeFlags=3, persistedTime=1601203263354}]奇怪的是,对于某些文件,这可以工作,而对于一些文件,它会产生这个错误,所有音频文件都位于内部存储的同一个位置。
编辑
介质with的值是用ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));求出的
另外,我要删除的文件不是由我的应用程序创建的
发布于 2022-10-13 12:43:18
试试这个方法。您需要使用父文件夹的SAF获得持久化uri权限,然后传递要删除的文件的uri & name。(我有一个模型类来处理这两个问题。)
public void deleteAPI29(ArrayList<Media> mediaList) {
Uri persistedUri = getContentResolver().getPersistedUriPermissions().get(0).getUri();
DocumentFile documentFile = DocumentFile.fromTreeUri(this, persistedUri);
for (int i = 0; i < mediaList.size(); i++) {
File file = new File(mediaList.get(i).getPath());
DocumentFile nextDocument = documentFile.findFile(file.getName());
try {
DocumentsContract.deleteDocument(getContentResolver(), nextDocument.getUri());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}https://stackoverflow.com/questions/64087565
复制相似问题