10

I have a DocumentFile defined in following two ways:

DocumentFile documentFile;
Uri documentFileUri;

I can delete a document file from the sd card via following methods:

  1. documentFile.delete();
  2. DocumentsContract.deleteDocument(contentResolver, documentFileUri);

But non of the above methods will delete the corresponding entry from the MediaStore.

What's the correct way to handle that? If I use the ContentProvider for deleting a local file, it will remove the File AND the row from the database (contentResolver.delete(localFileUri, null, null);). I would expect the same to happen if I use the DocumentsContract but it does not happen...

What I want

I want to instandly update the MediaStore. Normally I would call contentResolver.delete(documentFileUri, null, null); but this will fail with an exception that says, that the uri does not support deletions...

Question

Is there a more efficiant way to do it than my workaround?

Workaround

Currently I use following function to instantly update the media store after I deleted a DocumentFile:

public static boolean updateAfterChangeBlocking(String path, int timeToWaitToRecheckMediaScanner)
{
    final AtomicBoolean changed = new AtomicBoolean(false);
    MediaScannerConnection.scanFile(StorageManager.get().getContext(),
            new String[]{path}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    changed.set(true);
                }
            });

    while (!changed.get()) {
        try {
            Thread.sleep(timeToWaitToRecheckMediaScanner);
        } catch (InterruptedException e) {
            return false;
        }
    }

    return true;
}
4

1 回答 1

1

正如fatboy 指出的那样,这种行为是设计使然 - 记录在这个谷歌问题中:https ://issuetracker.google.com/issues/138887165

解决方案:

可能没有比我已经在我的问题中发布的更好的解决方案了:

  • DocumentFile通过对象或与它的URI和删除文件DocumentsContract.deleteDocument
  • 对于即时媒体商店更新(这就是我想要的),您必须手动更新媒体商店,例如MediaScannerConnection.scanFile(...)像我已经在我的问题中发布的那样调用
于 2019-08-13T06:42:16.673 回答