Skip to main content

How to specify download destination folder and file name using DownloadManager in Kotlin Android

How to specify download destination folder and file name using DownloadManager in Kotlin Android.

Here's a step-by-step tutorial on how to specify the download destination folder and file name using DownloadManager in Kotlin Android:

Step 1: Add permissions to the AndroidManifest.xml file

To enable file download, you need to add the following permissions to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Step 2: Create a download request

To download a file using DownloadManager, you need to create a download request. Here's an example of how to create a download request:

val url = "https://example.com/file.pdf"
val request = DownloadManager.Request(Uri.parse(url))

Step 3: Set the destination folder

To specify the download destination folder, you need to set the destination URI for the download request. Here's an example of how to set the destination folder:

val destinationFolder = "/storage/emulated/0/Download/"
val fileName = "file.pdf"
val destinationUri = Uri.fromFile(File(destinationFolder, fileName))
request.setDestinationUri(destinationUri)

In the above example, we set the destination folder to the "Download" folder on the internal storage and specify the file name as "file.pdf". You can modify the destination folder and file name according to your requirements.

Step 4: Set other optional parameters

You can also set other optional parameters for the download request, such as the title, description, and notification visibility. Here's an example of how to set these parameters:

request.setTitle("Downloading File")
request.setDescription("Please wait while the file is being downloaded")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

Step 5: Enqueue the download request

To start the file download, you need to enqueue the download request using the DownloadManager. Here's an example of how to enqueue the download request:

val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadId = downloadManager.enqueue(request)

The downloadId returned by the enqueue method can be used to track the progress or cancel the download if needed.

That's it! You have successfully specified the download destination folder and file name using DownloadManager in Kotlin Android.