I am downloading a PDF file from the web, and storing it in the documents folder of the android device, using DownloadManager API
. For that, I am using the method setDestinationInExternalPublicDir
, passing in Environment.DIRECTORY_DOCUMENTS
as the dirType, and the name of my file with the '.pdf' extension as the subPath parameter. The file is saved in the directory as expected, but the problem is that I can't retrieve it's Uri
so that I can use it in the following code (it is inside a Notification context):
val flags = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
}
val uri = getPDFUri(pdfFileName + DownloadUtils.FileExtensions.PDF)
setContentIntent(
PendingIntent.getActivity(
context,
1,
Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, "application/pdf")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION),
flags
)
)
The ideia is that when the user clicks on the notification, the app picker will show up, and the user will be able to choose, say, Adobe Acrobat Reader, and the app will open the downloaded file.
Both compileSdkVersion and targetSdkVersion are 33
I tried using FileProvider
, ContentResolver
, MediaStore
, but to no avail. I think I am doing something wrong, but I do not know what. Even tried using ChatGPT to generate some code, but no success either.
Thanks to @blackapps, I was able to find the solution. Or should I say, the case-specific solution. I was able to retrieve the Uri by using the method
DownloadManager.getUriForDownloadedFile
which works on Android 13. I will test to see if it works on older Android versions as well, and will update this answer after.
But I was unable to retrieve the Uri in another, generic way. If anyone knows how to do it without using the method from DownloadManager
, I would love to hear about.