【发布时间】:2014-02-17 07:05:51
【问题描述】:
我想将拍摄的照片添加到 MediaStore,以便图库应用可以找到它们(无需重新启动设备)。 应用的最小 sdk 为 9。任何帮助、博客或文档表示赞赏。
【问题讨论】:
标签: android android-mediascanner
我想将拍摄的照片添加到 MediaStore,以便图库应用可以找到它们(无需重新启动设备)。 应用的最小 sdk 为 9。任何帮助、博客或文档表示赞赏。
【问题讨论】:
标签: android android-mediascanner
在大多数设备上,您只需稍等片刻,就会自动检测到新照片。
如果您想立即刷新图库,您需要使用 MediaScanner 类,它将刷新图库 - 删除已删除的照片,添加新照片等等...
public void refreshGallery() {
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String newPhotoPath = "file:" + image.getAbsolutePath(); // image is the created file image
File file = new File(newPhotoPath);
Uri contentUri = Uri.fromFile(file);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
}
希望这有帮助!
【讨论】:
ACTION_MEDIA_MOUNTED 更改为ACTION_MEDIA_SCANNER_SCAN_FILE 解决了问题。编辑您的答案,以便我接受此为正确答案!
ACTION_MEDIA_SCANNER_SCAN_FILE 已弃用
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
在“保存”代码之后插入这行代码。
这将触发媒体扫描,所有文件夹中的所有媒体文件(“.nomedia”文件除外)都将更新并在图库中可见。
或
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
【讨论】:
好的,这是我的代码,它对我有用
getallimages(Environment.getExternalStorageDirectory());
我的功能在下面
private void getallimages(File dir)
{
String[] STAR = { "*" };
final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
ImageItem imageItem = new ImageItem();
if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
{
imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));
imageItem.id = id;
imageItem.selection = false; //newly added item will be selected by default
controller.images.add(imageItem);
}
}
}
【讨论】:
您可以要求 MediaScanner 扫描特定文件,即按需扫描您的图像文件。与仅要求 MediaScanner 扫描所有内容以查找新文件相比,这应该产生更少的开销。
【讨论】: