保存二维码到相册时遇到的问题
保存成功后查看相册会出现两张一样的,原因查看下面注释
public static void saveImage(Context context, Bitmap bmp) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Toast.makeText(context,"sdcard未使用",Toast.LENGTH_SHORT).show();
return;
}
// 首先保存图片
File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Toast.makeText(context,"保存失败",Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
} catch (IOException e) {
Toast.makeText(context,"保存失败",Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
}
bmp.recycle();
// 不需要插入到系统图库(最后刷新就好),否则会发现相册保存了两张二维码
/* try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
bmp, fileName, null);
} catch (Exception e) {
e.printStackTrace();
}*/
Toast.makeText(context,"保存成功",Toast.LENGTH_SHORT).show();
// 最后通知图库更新
// 这个方法无法指定保存路径和图片名,而且刷新将扫描整个SD卡,用户体验不好,所以看下面这个方法。
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
//发送广播通知系统图库刷新数据
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}