版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengxu_kuangrexintu/article/details/83069966
前言
在日常的Android开发当中,我们可能遇到保存图片的需求。这个功能是相对容易去实现的,但是今天我更新之前的项目的代码的时候出现了一个Android 7.0保存图片失败的情况。因为不是本人开发的,我将代码从头看起,看起来没有代码写的没有错误呀!我就有点头疼呀,到底是哪个环节没有写对呢?
上代码
private void saveImg() {
if (TextUtils.isEmpty(bean.getData().getWeixinImgUrl())) {
return;
}
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
showToast("保存失败,没有读写sd卡权限");
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/" + getContext().getPackageName() + "/img/" + bean.getData().getWeixinName() + ".png";
final File file = new File(path);
executorService.execute(new Runnable() {
@Override
public void run() {
try {
OutputStream os = new FileOutputStream(file);
URL url = new URL(bean.getData().getWeixinImgUrl());
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
bitmap.compress(Bitmap.CompressFormat.PNG, 90, os);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(), "图片保存到:" + file, Toast.LENGTH_LONG).show();
//发送广播给系统 告诉他多了张图片 刷新数据 这样的话就能在相册见到了
Uri uri = Uri.fromFile(file);
getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
}
});
os.flush();
os.close();
} catch (FileNotFoundException e) {
Looper.prepare();
showToast("保存失败");
Looper.loop();
} catch (MalformedURLException e) {
Looper.prepare();
showToast("保存失败");
Looper.loop();
} catch (IOException e) {
Looper.prepare();
showToast("保存失败");
Looper.loop();
}
}
});
}
解析问题以及解决方案
上面的代码看起来是没有问题,但是在Android7.0以上的手机就是会保存失败。琢磨了很久,我终于发现了问题所在了:没有用代码检测保存图片的文件是否存在,如果不存在的情况创建我们的保存路径的文件夹。加入这段代码就可以了
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
完美解决问题。