删除图像文件后刷新图库?

时间:2013-03-18 21:36:40

标签: android android-intent android-broadcast

我总是为我的问题找到以下答案:

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
            + Environment.getExternalStorageDirectory())));

但它不适用于我的系统(Nexus4 Android 4. ...)

我可以创建一个文件并将其添加到与此代码相关的Media-DB

Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);

“file”是我要添加的新图像文件。

删除文件后,我尝试按

刷新图库
Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
    Uri contentUri = Uri.parse("file://" + Environment.getExternalStorageDirectory());
    intent.setData(contentUri);
    context.sendBroadcast(intent);

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
            + Environment.getExternalStorageDirectory()))); 

但Galery仍有空占位符。

我不知道为什么?...

为了安全起见,我在AndroidManifest.xml中添加了我的Activity

<intent-filter>
            <action android:name="android.intent.action.MEDIA_MOUNTED" />
            <data android:scheme="file" /> 
        </intent-filter>

但结果是一样的。有什么想法来解决这个问题吗?

3 个答案:

答案 0 :(得分:13)

在KitKat之后,您无法发送Intent在整个设备的存储上运行MediaScanner,因为它是一个CPU I \ O密集型任务,如果每个应用程序都下载图像或删除一个,请调用意图电池很容易耗尽,因此他们决定阻止这种操作。您可以选择以下选项:

使用旧方式预先准备KitKat

传递你的filePath:

if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));
} else{


    MediaScannerConnection.scanFile(mContext,  filePath, 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.i("ExternalStorage", "Scanned " + path + ":");
        Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });

}

更可靠的方法是直接更新MediaStore

// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };

// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };

// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst()) {
    // We found the ID. Deleting the item via the content provider will also remove the file
    long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
    Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
    contentResolver.delete(deleteUri, null, null);
} else {
    // File not found in media store DB
}
c.close();

答案 1 :(得分:8)

检查以下代码段,以编程方式验证添加/删除/移动图像文件的所有案例,并使用图库应用程序来刷新数据

/***
 * Refresh Gallery after add image file programmatically 
 * Refresh Gallery after move image file programmatically 
 * Refresh Gallery after delete image file programmatically
 * 
 * @param fileUri : Image file path which add/move/delete from physical location
 */
public void refreshGallery(String fileUri) {

    // Convert to file Object
    File file = new File(fileUri);

    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        // Write Kitkat version specific code for add entry to gallery database
        // Check for file existence
        if (file.exists()) {
            // Add / Move File
            Intent mediaScanIntent = new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(new File(fileUri));
            mediaScanIntent.setData(contentUri);
            BaseApplication.appContext.sendBroadcast(mediaScanIntent);
        } else {
            // Delete File
            try {
                BaseApplication.appContext.getContentResolver().delete(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Images.Media.DATA + "='"
                                + new File(fileUri).getPath() + "'", null);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    } else {
        BaseApplication.appContext.sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                        + getBaseFolder().getAbsolutePath())));
    }
}

答案 2 :(得分:0)

对于 Xamarin C#,您可以使用以下代码!

<块引用>

只需将完整的文件路径传递给数组

 Android.Media.MediaScannerConnection.ScanFile(Android.App.Application.Context, new string[] { deletedImageFilePath}, null, null);