Android11文件存储(1)

本文介绍了如何在Android 11及更高版本中保存图片到相册,包括使用`Environment.getExternalStorageDirectory()`创建文件路径,处理权限以及通过ContentResolver插入到MediaStore。此外,还提供了截图并保存的示例代码。
摘要由CSDN通过智能技术生成

String fileName = Environment.getExternalStorageDirectory() + File.separator + “DCIM”

  • File.separator + “demo” + File.separator;

try {

File file = new File(fileName);

if (!file.exists()) {

file.mkdirs();

}

MLog.e(“saveAndGetImage:” + file);

File filePath = new File(file + “/” + imgName + “.png”);

MLog.e(“filePath:” + filePath);

FileOutputStream out = new FileOutputStream(filePath); //保存到本地,格式为JPEG

if (outB.compress(Bitmap.CompressFormat.PNG, 100, out)) {

out.flush();

out.close();

}

MLog.e(“saveAndGetImage:END”);

//刷新图库

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//高于22版本要手动授权

// 检查该权限是否已经获取

int i = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

// 权限是否已经 授权 GRANTED—授权 DINIED—拒绝

if (i != PackageManager.PERMISSION_GRANTED) {

// 提示用户应该去应用设置界面手动开启权限

} else {

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(filePath)));

}

} else {

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(filePat

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值