保存图片之后,图库中不能看到的问题解决

写作原因:

在做IM的时候有发送图片的需求,进而引申处图片的保存功能,添加保存功能的时候发现保存后再去发送图片的时候,刚才保存的图片没有展示出来。


问题解决:

在保存成功后需要将文件插入到系统图库,

try {
                                MediaStore.Images.Media.insertImage(MwApplication.getContext().getContentResolver(),
                                        mFile.getAbsolutePath(), uuid, null);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

最开始的时候做了这个动作,发现问题还是存在,查找文档发现需要通知系统图库更新,代码如下

MwApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mFile.getAbsolutePath())));

完整代码如下

if (FileUtil.isFileExist(uuid + ".jpg", Environment.DIRECTORY_DCIM)) {
                            Toast.makeText(MwApplication.getContext(), "文件已存在", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        File mFile = FileUtil.createFile(bytes, uuid + ".jpg", Environment.DIRECTORY_DCIM);
                        if (mFile != null) {
                            Toast.makeText(MwApplication.getContext(), "保存成功" +
                                    "path : " + mFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                            // 保存成功后把文件插入到系统图库
                            try {
                                MediaStore.Images.Media.insertImage(MwApplication.getContext().getContentResolver(),
                                        mFile.getAbsolutePath(), uuid, null);
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            // 插入图库后通知图库更新
                            MwApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mFile.getAbsolutePath())));
                        } else {
                            Toast.makeText(MwApplication.getContext(), MwApplication.getContext().getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                        }

猜你喜欢

转载自blog.csdn.net/wanzhuanit/article/details/79695069