我正在使用一个应用程序,在该应用程序中我们将其截屏并将其保存在DCIM / MYFOLDER文件夹中。我之前的代码包括运行正常的Android.OS.Environment.GetExternalStoragePublicDirectory。
我已升级我的SDK以支持AndroidQ。我的Compile SDK设置为Android 10.0Q。现在,上面的代码在IDE中已显示为已弃用,并且未将屏幕快照保存到指定的文件夹。我更新了我的代码,现在可以在Android 10设备上使用,但对于以前的设备则无法使用。
我不想在if else语句中使用两个平台的两个代码,因为在Android Q中不推荐使用前一个。
这是我当前的代码,该代码适用于Android 10设备,但不适用于Android 8:
var screenshot = CaptureAsyncValue();
var imageName = number + ".png";
var IMAGES_FOLDER_NAME = "MYFOLDER";
ContentResolver resolver = _currentActivity.ContentResolver;
ContentValues contentValues = new ContentValues();
contentValues.Put(MediaStore.MediaColumns.DisplayName, imageName);
contentValues.Put(MediaStore.MediaColumns.MimeType, "image/png");
contentValues.Put(MediaStore.MediaColumns.RelativePath, "DCIM/" + IMAGES_FOLDER_NAME);
// this URI variable is null for devices below Android 10 hence the next line of code crashes
Uri imageUri = resolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
var fos = resolver.OpenOutputStream(imageUri);
await fos.WriteAsync(screenshot);
fos.Flush();
fos.Close();
要么使用android:requestLegacyExternalStorage="true"
来实现向后/向前兼容性,要么通过不请求旧版外部存储并具有两个不同的存储位置来正确地进行修复。