适配 Android10 内部存储图片显示问题
16lz
2021-01-23
外部存储将被废弃:filePath:/storage/emulated/0/com.aaa.bbb/图片
对应方法:Environment.getExternalStorageDirectory()
官方接口说明:https://developer.android.google.cn/reference/kotlin/android/os/Environment?hl=en#getexternalstoragedirectory
官方Android 10 隐私说明:https://developer.android.google.cn/about/versions/10/privacy/changes
期望路径文件路径:filePath:/storage/emulated/0/Android/data/com.aa a.bbb/files/Pictures/图片
对应方法context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
引发问题:在相册无法显示已保存的图片
解决方案:可根据自己的情况做适配
/** * 将bitmap存成文件 * * @param context * @param bitmap * @param imageName */ public static String saveBitmap(Context context, Bitmap bitmap, String imageName) { FileOutputStream fos = null; OutputStream os = null; BufferedInputStream inputStream = null; File imageFile = null; try { //生成路径// File filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),APP_FOLDER_PHOTO); File filePath = new File(StringUtils.getString(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "/", context.getPackageName(), "/photo/")); Log.e("aaa->"," filePath:" + filePath.getPath() + " fileAbsolutePath:" + filePath.getAbsolutePath()); if (!filePath.exists()) { boolean is = filePath.mkdirs(); Log.e("aaa->","is: " + is); } //获取文件 imageFile = new File(filePath, imageName); fos = new FileOutputStream(imageFile); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DESCRIPTION, "This is an image"); values.put(MediaStore.Images.Media.DISPLAY_NAME, imageName); values.put(MediaStore.Images.Media.MIME_TYPE, "image/png"); values.put(MediaStore.Images.Media.TITLE, "Image.png"); values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/"); Uri external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver resolver = context.getContentResolver(); Uri insertUri = resolver.insert(external, values); inputStream = new BufferedInputStream(new FileInputStream(imageFile)); if (insertUri != null) { os = resolver.openOutputStream(insertUri); } if (os != null) { byte[] buffer = new byte[1024 * 4]; int len; while ((len = inputStream.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); } //通知系统相册刷新 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile))); return imageFile.getPath(); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { fos.close(); os.close(); inputStream.close(); imageFile.delete();// 这里删除源文件不存在 但相册可见 } catch (IOException e) { e.printStackTrace(); } } }
参考:https://www.okcode.net/article/91099
更多相关文章
- 图片旋转的两种方法
- Android 使用颜色矩阵改变图片颜色,透明度,亮度
- android 显示gif格式的图片
- 详细讲解Android的图片下载框架UniversialImageLoader之磁盘缓存
- 手机相册的基本使用
- OOM的出现及解决(加载图片)
- 【Android 开发】:UI控件之 ImageView 实现适屏和裁剪图片的功能
- Android底下多线程下载远程图片
- Android APP内存优化之图片优化