Trying to save a PDF file in downloads directory, but after getExternalStoragePublicDirectory
got completely deprecated after Android Q, there is no way to save files in any other location than DCIM or Pictures folder as the following exception got thrown when trying to save file there.
IllegalArgumentException: Primary directory Download not allowed for content://media/external/images/media; allowed directories are [DCIM, Pictures]
Have the following code.
private fun saveFile(input: ByteArray) {
val fileName = "myFile.pdf"
val outputStream = if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
val file = File(directory, fileName)
FileOutputStream(file)
} else {
val resolver = context.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "images/*")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let {
resolver.openOutputStream(it)
}
}
outputStream?.use { stream ->
stream.write(input)
}
}
Obviously when changing the path to DIRECTORY_DCIM, everything works as expected, but due to requirements the file should be saved to downloads as previously. Would appreciate any help.
If your app is used on a device that runs Android 9 or lower, or if your app has temporarily opted out of scoped storage, you must request the READ_EXTERNAL_STORAGE permission to access media files. If you want to modify media files, you must request the WRITE_EXTERNAL_STORAGE permission, as well.
If you want to modify media files, you must request the WRITE_EXTERNAL_STORAGE permission, as well. Note: If your app's use case isn't covered by scoped storage, file a feature request and temporarily opt out of scoped storage.
If your app targets Android 12 (API level 31) or higher, you can request that users grant your app access to the Media management special permission. This permission allows your app to do each of the following without needing to prompt the user for each file operation:
In order to access media files using native files methods on Android 10, you must also request the READ_EXTERNAL_STORAGE permission. When accessing media content, keep in mind the considerations discussed in the following sections.
Wasn't setting the correct Uri for file saving, for downloads it should be
resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
blackapps Thanks for pointing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With