简体   繁体   English

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

[英]Refresh the Gallery after deleting an image file?

I always found the following answer for my Question:我总是为我的问题找到以下答案:

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

but it do not work on my System (Nexus4 Android 4. ...)但它不适用于我的系统(Nexus4 Android 4. ...)

I can create a File and add it to the Media-DB whith this code我可以创建一个文件并将其添加到带有此代码的 Media-DB

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

Where "file" is the new image-file i want to add.其中“文件”是我要添加的新图像文件。

after deleting the File I try to refresch the gallery by删除文件后,我尝试通过以下方式刷新图库

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

or要么

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

but there are still empty placeholder in the Galery.但 Galery 中仍然有空的占位符。

I do not know why?...我不知道为什么?...

To be on the safe side I add too my Activity in the AndroidManifest.xml为了安全起见,我在 AndroidManifest.xml 中也添加了我的 Activity

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

but the result is the same.但结果是一样的。 Any idea to solve the problem?有解决问题的想法吗?

After the KitKat you can't send the Intent to run the MediaScanner on whole device's storage, because it is a CPU I\\O intensive task and if every single app that download an image or delete one, call that intent battery would drain easily, hence they have decided to block that operation.在 KitKat 之后,您无法发送 Intent 在整个设备的存储上运行MediaScanner ,因为这是一项 CPU I\\O 密集型任务,如果每个应用程序下载图像或删除图像,调用该 Intent 电池很容易耗尽,因此他们决定阻止该操作。 Here are your options:以下是您的选择:

Use the old way for pre-KitKat使用旧方式进行前 KitKat

Pass your 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);
        }
    });

}

A more reliable approach is to update the MediaStore directly:更可靠的方法是直接更新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();

Check below code snippet to verify all the cases for add/delete/move image file programmatically and intimate the gallery app to refresh the data检查以下代码片段以验证以编程方式添加/删除/移动图像文件的所有情况,并通知图库应用程序刷新数据

/***
 * 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())));
    }
}

For Xamarin C# you can Use following Code!对于 Xamarin C#,您可以使用以下代码!

Just pass the full File path to the Array只需将完整的文件路径传递给数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM