androidpdfsavemediaandroid-10.0

Primary directory Download not allowed for media


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.


Solution

  • 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.