10

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

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);

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

删除文件后,我尝试通过

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()))); 

但是画廊中仍然有空的占位符。

我不知道为什么?...

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

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

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

4

3 回答 3

14

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

使用以前的 KitKat 方法

传递你的文件路径:

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();
于 2015-01-23T09:10:39.057 回答
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())));
    }
}
于 2015-01-21T05:19:35.990 回答
0

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

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

 Android.Media.MediaScannerConnection.ScanFile(Android.App.Application.Context, new string[] { deletedImageFilePath}, null, null); 
于 2020-12-31T19:27:11.153 回答