在Android 11中,应用程序无法直接访问外部存储器中的大多数目录,因此需要使用不同的方法来访问这些目录。以下是一个示例代码,通过使用MediaStore访问相册并保存图像文件的方式来解决这个问题:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "MyApp");
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
OutputStream imageOut = resolver.openOutputStream(imageUri);
// write the bitmap to the output stream
imageOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// your code for writing to external storage on pre-Android 11 devices
}