I am downloading files using Android's Download Manager and storing the files on removeable SD Card. It is working on Android OS6 Marshmallow and Android OS8 Oreo but NOT working on Android OS9 PIE.
setDestinationURI()
is being used to store files on removable SD Card.
private fun setExternalStorageDir() {
val arrayOfFiles = getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS) //as per official documentation
parentDirectory = if (arrayOfFiles.size > 1 && arrayOfFiles[0] != null && arrayOfFiles[1] != null)
arrayOfFiles[1].toString() //External Storage Dir Path being retrieved successfully
else if (arrayOfFiles.size == 1 && arrayOfFiles[0] != null)
arrayOfFiles[0].toString() //Internal Storage being treated as External Storage by Android
else
Environment.DIRECTORY_DOWNLOADS //Internal Storage Download Folder
}
//Request Builder Code. Request is being sucessfully executed in OS 6 and 8 respectively
val request = DownloadManager.Request(downloadUri).apply {
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
setAllowedOverRoaming(false)
setTitle("Image Downloading")
setNotificationVisibility(VISIBILITY_VISIBLE)
setDestinationUri(Uri.fromFile(File("$parentDirectory/sampleImage.png")))
}
private val onDownloadComplete = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
val query = DownloadManager.Query()
query.setFilterById(reference)
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val cursor = downloadManager.query(query)
cursor.moveToFirst()
val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
val status = cursor.getInt(statusIndex)
if (status == DownloadManager.STATUS_SUCCESSFUL) {
} else if (status == DownloadManager.STATUS_FAILED) {
Log.e("DOWNLOAD BROADCAST", "Download failed")
val reasonIndex = cursor.getColumnIndex(DownloadManager.COLUMN_REASON)
val reason = cursor.getInt(reasonIndex)
Log.e("DOWNLOAD BROADCAST", reason.toString())
}
}
}
DownloadManager fails executing request on Android PIE OS9 with status 403
PS: Min SDK 21, Targetted 29. Runtime Permissions are handled.
W/DownloadManager: [37] Stop requested with status FILE_ERROR: Failed to generate filename: java.io.IOException: Permission denied"