How to trigger MediaScan on Nexus 7?

前端 未结 3 1393
感情败类
感情败类 2020-12-03 12:45

Because I want to make sure the MediaStore has the latest information without having to reboot I\'d like to trigger the MediaScanner using the popular way I found on SO

相关标签:
3条回答
  • 2020-12-03 13:18

    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) {
        ... 
    }
    
    0 讨论(0)
  • 2020-12-03 13:21

    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.

    0 讨论(0)
  • 2020-12-03 13:31

    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.

    0 讨论(0)
提交回复
热议问题