android10图片,适配 Android10 内部存储图片显示问题

外部存储将被废弃: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值