To download a file using the DownloadManager and save it to your app's private storage directory, you can pass null
as the directory parameter in the setDestinationInExternalFilesDir
method. This will ensure that the file is downloaded to your app's private file storage, which is not accessible to other apps or the user.
Example
val request = DownloadManager.Request(Uri.parse(fileUrl))
.setDestinationInExternalFilesDir(context, null, fileName)
Complete Example
Here is a complete example of a function that downloads a file to your app's private folder, just pass to it the context, fileUrl, fileName and fileDescription, and you can modify it as your needs:
private fun downloadFile(
context: Context,
fileUrl: String,
fileName: String,
fileDescription: String
) {
val request = DownloadManager.Request(Uri.parse(fileUrl))
.setTitle(fileName)
.setDescription(fileDescription)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalFilesDir(context, null, "$fileName.${getFileExtension(fileUrl)}")
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager
downloadManager?.enqueue(request)
}
This function is used to get the file extension to make it work without problems:
private fun getFileExtension(fileUrl: String): String {
return MimeTypeMap.getFileExtensionFromUrl(fileUrl)
}
You can get a refrence to the private app file like this:
val privateDir = context.getExternalFilesDir(null)
Private folder path will be:
val path = "/storage/emulated/0/Android/data/com.your.package/files/"
Make sure to change "com.your.package" to your app package name.
Or you can get it from the file reference itself:
val path = privateDir?.absolutePath
Example
If you download a file "image.png", the path for the image will be:
val imagePath = "/storage/emulated/0/Android/data/com.your.package/files/image.png"