首页 > 解决方案 > 如何使用媒体扫描仪减少媒体的扫描时间?

问题描述

我正在使用以下代码在图像删除后扫描媒体,但这需要太多时间。我想在图像删除后快速更新我的图像列表。如何做到这一点?

if (Build.VERSION.SDK_INT >= 14) {
    Log.e("-->", " >= 14");
    MediaScannerConnection.scanFile(this, new String[]{String.valueOf(Environment.getExternalStorageDirectory())}, null, new MediaScannerConnection.OnScanCompletedListener() {
        /*
         *   (non-Javadoc)
         * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
         */
        public void onScanCompleted(String path, Uri uri) {
            Log.e("ext str gal", "Scanned " + path + ":");
            Log.e("ext str gal", "-> uri=" + uri);
        }
    });
} else {
    Log.e("-->", " < 14");
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}

标签: android

解决方案


我得到了答案。使用 ContentResolver 扫描 mediaStore。我希望它对某人有所帮助。

public void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {

    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }

    try{

        final Uri uri = MediaStore.Files.getContentUri("internal");
        final int result = contentResolver.delete(uri,
                MediaStore.Files.FileColumns.DATA + "=?", new String[] {canonicalPath});

        if (result == 0) {
            final String absolutePath = file.getAbsolutePath();

            if(!absolutePath.equalsIgnoreCase(canonicalPath)){
                contentResolver.delete(uri,
                        MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});

            }
        }

//remove thumbnail of deleted image
        Intent mediaScanIntent = new   Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        getContext().sendBroadcast(mediaScanIntent);


    }catch (Exception e){
        e.printStackTrace();
    }
}

推荐阅读