适配 Android10 内部存储图片显示问题
程序员文章站
2024-02-14 22:55:34
...
外部存储将被废弃: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