The files downloaded from any web browser usually get stored in the Downloads folder. It is a common requirement for our app to access the Downloads folder to either create a new file or access the existing files.
In this article, we will see how to access the downloads folder using kotlin.
Declare permissions
Let us start by adding the required permission in the AndroidManifest.xml file to access the external storage.
Open the file from the Android Studio (or file explorer) and add the following lines of code.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The above permissions are needed to read and write files on the external storage.
Request users permission
From Android 6.0, to access any privacy-related functionalities we have to request permissions at runtime.
We have to use ActivityCompat.requestPermissions
a method either in the activity or the method and the response from the user should be handled using the onRequestPermissionsResult
method.
Following is an example:
private val REQUEST_PERMISSION_CODE = 1001
private fun checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
), REQUEST_PERMISSION_CODE)
} else {
// Permissions already granted
accessDownloadsFolder()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
accessDownloadsFolder()
} else {
// Permission denied
// Handle accordingly
}
}
}
Accessing the downloads folder
Once we have the necessary permissions, then it’s go-ahead for us to access the Downloads folder using the Environment.getExternalStoragePublicDirectory
method with the parameter as DIRECTORY_DOWNLOADS
.
This method returns a File object which represents the Downloads folder.
private fun accessDownloadsFolder() {
val downloadsFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
if (downloadsFolder != null && downloadsFolder.exists()) {
val files = downloadsFolder.listFiles()
for (file in files) {
// Perform operations on individual files
}
} else {
// Downloads folder not found
// Handle accordingly
}
}
In the above code, we are checking if the folder exists before performing any operations on it by retrieving the Downloads folder using the Environment.getExternalStoragePublicDirectory
method.