Search code examples
androidandroid-studioandroid-gallerymediastoreandroid-mediascanner

Refresh MediaStore for Images & Videos


I moving and deleting lots of images and videos as per my requirement and now i am scan media by using

Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(scanFileIntent);

all working fine but sometime freeze the screen, i think some issue in MediaScanner.

And my second quetion is how to scan all media Store rether than scan perticuler File.

Thanks in Advance!!


Solution

  • You should try this solution for amove and delete the image.

    Pass file directory path inside deleteRecursive(fileOrDirectory) and you can delete multiple and the single image from file or directory.

    public void deleteRecursive(File fileOrDirectory) {
        if (!fileOrDirectory.isDirectory()) return;
        File[] childFiles = fileOrDirectory.listFiles();
        if (childFiles == null) return;
        if (childFiles.length == 0) {
            fileOrDirectory.delete();
        } else {
            for (File childFile : childFiles) {
                deleteRecursive(childFile);
                DeleteAndScanFile(MainActivity.this, childFile.getPath(), childFile);
            }
        }
    
    
    }
    
    private void DeleteAndScanFile(final Context context, String path,
                                   final File fi) {
        String fpath = path.substring(path.lastIndexOf("/") + 1);
        try {
            MediaScannerConnection.scanFile(context, new String[]{Environment
                            .getExternalStorageDirectory().toString()
                            + "/abc/"
                            + fpath.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            if (uri != null) {
                                context.getContentResolver().delete(uri, null,
                                        null);
                            }
                            fi.delete();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    It's Good work for me, Hope this help you...if you need any help you can ask