How to trigger MediaScan on Nexus 7?

我们两清 提交于 2019-11-27 14:31:10

using the popular way I found on SO

Faking ACTION_MEDIA_MOUNTED broadcasts has never been an appropriate solution IMHO.

Any ideas/alternatives?

Use MediaScannerConnection, such as via its scanFile() static method.

Here's the sample code based on CommonsWare's answer:

MediaScannerConnection.scanFile(activity, new String[]{path}, null,
                                new MediaScannerConnection.OnScanCompletedListener() {
    @Override
    public void onScanCompleted(final String path, final Uri uri) {
        Log.i(TAG, String.format("Scanned path %s -> URI = %s", path, uri.toString()));
    }
});

Even though in most of the cases, where one knows the files to be added/updated/etc. to the MediaStore, one should follow CommonsWare's answer, I wanted to post the my solution where I need to do it the rough way because I don't know the file paths. I use this mostly for testing/demoing:

Uri uri = Uri.fromFile(Environment.getExternalStorageDirectory());
activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, uri));

BTW, no permissions are necessary for either solution.

My answer is a little late, but it might help those, who save a new file, and would like to extend the media store by just that file on Android Kitkat: On Android Kitkat the intent ACTION_MEDIA_MOUNTED is blocked for non-system apps (I think, because scanning the whole filesystem is pretty expensive). But it is still possible to use the intent ACTION_MEDIA_SCANNER_SCAN_FILE to add a file to the media store:

File f = new File(path to the file you would like to add to the media store ...);
try {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri uri = Uri.fromFile(f);
    mediaScanIntent.setData(uri);
    sendBroadcast(mediaScanIntent);
} catch(Exception e) {
    ... 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!