My app's minSdkVersion is 21 and targetSdkVersion is 30. I need to save image to external storage (to Pictures folder)
So, here's saveImage function:
fun saveImage(context: Context) {
val fileName = "${System.currentTimeMillis()}.png"
val fileType = "image/png"
val folder = "MyApp"
val imageQuality = 100
val write: (OutputStream) -> Boolean = { outputStream ->
this.compress(Bitmap.CompressFormat.PNG, imageQuality, outputStream)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, fileType)
put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$folder")
}
context.contentResolver.let {
it.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let { uri ->
it.openOutputStream(uri)?.let(write)
}
}
} else {
val imagesDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.toString() + File.separator + folder
val file = File(imagesDir)
if (!file.exists()) {
file.mkdir()
}
val image = File(imagesDir, fileName)
write(FileOutputStream(image))
}
}
Also I have this permission in Manifest file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
This is working ok, but getExternalStoragePublicDirectory is deprecated in API 29+.
Is there a way to get rid of this deprecated function? Right now I just suppress the warning, but it feels kinda bad.