如何在android中运行媒体扫描程序

pru*_*ddy 15 android android-camera android-gridview android-mediascanner

我想在捕获图像时运行媒体扫描仪.捕获后,图像在网格视图中更新.为此,我需要运行媒体扫描仪.我找到了两个运行媒体扫描程序的解决方案,一个是广播 事件,另一个是运行媒体扫描程序类.我认为在Ice Cream Sandwich(4.0)中引入了媒体扫描程序类.在版本之前需要设置广播事件来运行媒体扫描程序.

任何人都可以指导我如何以正确的方式运行媒体扫描仪.

bob*_*ble 29

如果您知道文件名,我发现在特定文件上运行媒体扫描程序(与运行它以扫描媒体的所有文件)最好(更快/最少开销).这是我使用的方法:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

当需要在多个文件上运行时(例如初始化具有多个图像的应用程序时),我在初始化时保留新图像文件名的集合,然后为每个新图像文件运行上述方法.在下面的代码中,addToScanList添加要扫描到的文件ArrayList<T>,并scanMediaFiles用于启动对阵列中每个文件的扫描.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)