how to run media scanner in android

孤街醉人 提交于 2019-11-26 18:50:33

I have found it best (faster/least overhead) to run media scanner on a specific file (vs running it to scan all files for media), if you know the filename. Here's the method I use:

/**
 * Sends a broadcast to have the media scanner scan a file
 * 
 * @param path
 *            the file to scan
 */
private void scanMedia(String path) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    Intent scanFileIntent = new Intent(
            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
    sendBroadcast(scanFileIntent);
}

When needing to run on multiple files (such as when initializing an app with multiple images), I keep a collection of the new images filenames while initializing, and then run the above method for each new image file. In the below code, addToScanList adds the files to scan to an ArrayList<T>, and scanMediaFiles is used to initiate a scan for each file in the array.

private ArrayList<String> mFilesToScan;

/**
 * Adds to the list of paths to scan when a media scan is started.
 * 
 * @see {@link #scanMediaFiles()}
 * @param path
 */
private void addToScanList(String path) {
    if (mFilesToScan == null)
        mFilesToScan = new ArrayList<String>();
    mFilesToScan.add(path);
}

/**
 * Initiates a media scan of each of the files added to the scan list.
 * 
 * @see {@see #addToScanList(String)}
 */
private void scanMediaFiles() {
    if ((mFilesToScan != null) && (!mFilesToScan.isEmpty())) {
        for (String path : mFilesToScan) {
            scanMedia(path);
        }
        mFilesToScan.clear();
    } else {
        Log.e(TAG, "Media scan requested when nothing to scan");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!