Story
Before Android 4.4, we could simply send a broadcast to launch a media scanner in any specific file, folder, or even in the root directory of the repository. But with 4.4 KitKat, this has been fixed by Android developers.
Why am I saying a fix? The reason is simple. Sending broadcasts using MEDIA_MOUNTED in the root directory is very expensive. Starting a Media Scanner is an expensive operation, and the situation gets even worse when a user has many files in storage structures and deep folders.
Before Android 4.4
Keep it straight and simple. If you have targeted your app to Android 4.4. But keep in mind not to use it in the root directory unless absolutely necessary.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
From Android 4.4
There are two ways for you.
i) The first one is very similar to the previous example, but may not work efficiently and is not recommended either.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
ii) Now let's move on to the most recommended and effective solution to this problem.
Add paths to files of files that have been updated, for example, in String type ArrayList
ArrayList<String> toBeScanned = new ArrayList<String>(); toBeScanned.add(item.getFilePath());
Now you need to run the staticFlashFile () static method of the MediaScannerConnection class and pass in a String array containing a list of all the files that have been updated and should be scanned.
You can also send a response to the listener when the scan is complete for individual files.
String[] toBeScannedStr = new String[toBeScanned.size()]; toBeScannedStr = toBeScanned.toArray(toBeScannedStr); MediaScannerConnection.scanFile(getActivity(), toBeScannedStr, null, new OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { System.out.println("SCAN COMPLETED: " + path); } });