I am trying to download PDF file from the web (url) in selected dir. I am using the below to open the dir picker
val directoryPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocumentTree()
) { uri ->
selectedDirectoryUri = uri
}
and once the dir is selected I am downloading the pdf.
fun downloadPdf(context: Context, pdfUrl: String, pdfTitle: String, directoryUri: Uri?) {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val request = DownloadManager.Request(Uri.parse(pdfUrl))
.setTitle(pdfTitle)
.setMimeType("application/pdf")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
// Set the destination directory to the selected directory URI
if (directoryUri != null) {
val directory = DocumentFile.fromTreeUri(context, directoryUri)
if (directory != null && directory.exists() && directory.isDirectory) {
request.setDestinationInExternalPublicDir(
directoryUri.toString(),
pdfTitle
)
}
}
val downloadId = downloadManager.enqueue(request)
// Store download status for observing in the Composable
_downloadStatus.value = DownloadStatus(downloadId)
}
The download manager completed the download and sends me a notification from where I can open the pdf but its not saved in the selected dir.
request.setDestinationInExternalPublicDir() has two parameters. The first one a folder name of a public dir the second one a file name.
It makes little sense to let the user choose a directory if you cannot decode a folder name from the uri.
You better determine the public dir yourself.
Or let it choose from a public dir list.
You should also realise that the user could choose DCIM or Pictures directory. But in both .pdf files cannot be saved.