Android创建图片后图库不显示
问题原因
创建图片时未插入数据到系统的Media Provider
该数据库位于/data/data/com.android.providers.media/database/external.db
解决方案
1. 通过MediaSore的InsertImage方法插入图片信息
/**
* Insert an image and create a thumbnail for it.
*
* @param cr The content resolver to use
* @param imagePath The path to the image to insert
* @param name The name of the image
* @param description The description of the image
* @return The URL to the newly created image
* @throws FileNotFoundException
*/
public static final String insertImage(ContentResolver cr, String imagePath,
String name, String description) throws FileNotFoundException {}
例如
try{
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
注:通过MediaStore插入图片数据时,系统会在 /DCIM/Camera 路径下生成一张缩略图,插入的数据Data也是该缩略图的路径,而并非原路径,而该方法的返回值便是缩略图Uri.toString()。所以当你删除原图片时,图库里的图也不会被删除。
2. 发送广播给Media Scanner,让其扫描该媒体文件
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
注:这种方式插入的数据是原图片路径且不会生成缩略图,所以当你删除原文件夹图片时,图库中的图片也会被删除。