从SDCard删除图像后如何刷新图库

And*_*Dev 9 android android-mediascanner

删除Android SD卡上的图像时,有时图像被正确删除但在图库中仍然保留已删除图像的预览.点击它时,它将作为黑色图像加载.要解决此问题,您需要运行MediaScanner.但是此代码不起作用,并且评论图像的预览仍保留在图库中.

任何人都知道如何解决这个问题

Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri); 
sendBroadcast(mediaScanIntent);
Run Code Online (Sandbox Code Playgroud)

Yar*_*lyk 17

您应该从mediaStore中删除它

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }
    final Uri uri = MediaStore.Files.getContentUri("external");
    final int result = contentResolver.delete(uri,
            MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});
    if (result == 0) {
        final String absolutePath = file.getAbsolutePath();
        if (!absolutePath.equals(canonicalPath)) {
            contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


kal*_*pvs 11

虽然

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Run Code Online (Sandbox Code Playgroud)

仅适用于4.4的系统应用程序

这是另一种解决方案.. 通过你删除或添加的图像的路径,如果图像被删除图像通过true或如果添加图像到库然后通过false.

    /**
 * Scanning the file in the Gallery database
 * 
 * @param path
 * @param isDelete
 */
private void scanFile(String path, final boolean isDelete) {
    try {
        MediaScannerConnection.scanFile(context, new String[] { path },
                null, new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        if (isDelete) {
                            if (uri != null) {
                                context.getContentResolver().delete(uri,
                                        null, null);
                            }
                        }
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)