首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Android中使用DocumentFile删除文件?

如何在Android中使用DocumentFile删除文件?
EN

Stack Overflow用户
提问于 2020-09-27 10:45:59
回答 1查看 516关注 0票数 1

用文档uri删除文件的方法

代码语言:javascript
复制
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错误

代码语言:javascript
复制
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)));求出的

另外,我要删除的文件不是由我的应用程序创建的

EN

回答 1

Stack Overflow用户

发布于 2022-10-13 12:43:18

试试这个方法。您需要使用父文件夹的SAF获得持久化uri权限,然后传递要删除的文件的uri & name。(我有一个模型类来处理这两个问题。)

代码语言:javascript
复制
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();
            }
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64087565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档