一、背景介绍
这几天,我在为公司同事开发一款危废管理的app,需要根据相关信息生成二维码,这一功能已实现(见 Android 应用开发学习-生成二维码(使用华为统一扫描服务 Scan Kit))。
二、存在的问题
本软件提供的将生成的二维码保存为图片的功能,关键代码如下:
// 将二维码保存为图片
private void saveCodeToPic() {
// 略 ...
// 设置图像的保存路径
// 保存路径在/PICTURES/wasteqrcode/ 文件夹下
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "wasteqrcode");
if (!file.exists()) {
boolean success = file.mkdirs();
}
String fileName = textType + "-" + code + ".jpeg";
String filePath = file + File.separator + fileName;
FileUtil.saveImage(filePath, bitmap, this);
// 略 ...
}
// 把位图数据保存到指定路径的图片文件
public static void saveImage(String path, Bitmap bitmap, Context context) {
// 根据指定的文件路径构建文件输出流对象
try (FileOutputStream fos = new FileOutputStream(path)) {
// 把位图数据压缩到文件输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
我在软件中将图片文件的保存路径设置为 /PICTURES/wasteqrcode/ 文件夹。可以通过手机自带的文件管理应用找到,但是却不能通过相册查看,感觉不方便。
三、问题的解决
这些天通过开发和学习,我对Android系统有了更多的了解。我的app生成的图片无法在相册中查看,是因为没有将相关的信息通知相册,相册自然不知道。只要能将图片生成的信息通知给相册,这个问题就解决了。
再次询问万能的度娘,一番搜索后,总算找到了一篇相关的文章
这篇文章里有现成的代码,基本上照搬过来就OK了。修改后的代码如下:
// 将二维码保存为图片
private void saveCodeToPic() {
// 略 ...
// 设置图像的保存路径
// 保存路径在/PICTURES/wasteqrcode/ 文件夹下
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "wasteqrcode");
if (!file.exists()) {
boolean success = file.mkdirs();
}
String fileName = textType + "-" + code + ".jpeg";
String filePath = file + File.separator + fileName;
FileUtil.saveImage(filePath, bitmap, this);
// 略 ...
}
// 把位图数据保存到指定路径的图片文件
public static void saveImage(String path, Bitmap bitmap, Context context) {
// 根据指定的文件路径构建文件输出流对象
try (FileOutputStream fos = new FileOutputStream(path)) {
// 把位图数据压缩到文件输出流中
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
File photo = new File(path);
updatePhotoMedia(photo, context);
} catch (Exception e) {
e.printStackTrace();
}
}
//更新图库
private static void updatePhotoMedia(File file , Context context){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
context.sendBroadcast(intent);
}
代码改好后,重新进行调试,生成一个二维码并保存为图片,这次,可以在相册中看到我的app生成的二维码图片了。