I am using downloadManager to download large files from server, and I wanted to store these files in my removable storage like SD card or USB(pendrive). My download location is /storage/511B-14E9/Media . I can successfully created the Media folder in my removable storage. But the download files are not saved in this location.
Permissions in Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
android:requestLegacyExternalStorage="true"
Method to find USB
fun getUSB(): String? {
val storageDirectory = File("/storage")
if (!storageDirectory.exists()) {
Log.e(
"ZZZZ",
"getUSB: '/storage' does not exist on this device"
)
return ""
}
val files = storageDirectory.listFiles()
if (files == null) {
Log.e(
"ZZZZ",
"getUSB: Null when requesting directories inside '/storage'"
)
return ""
}
val possibleUSBStorageMounts: ArrayList<String> = ArrayList()
for (file in files) {
val path = file.path
if (path.contains("emulated") ||
path.contains("sdcard") ||
path.contains("self")
) {
Log.d("ZZZZ", "getUSB: Found '$path' - not USB")
} else {
possibleUSBStorageMounts.add(path)
}
}
if (possibleUSBStorageMounts.size == 0) {
setErrorLog(44,"Did not find any possible USB mounts")
return ""
}
if (possibleUSBStorageMounts.size > 1) {
Log.d(
"ZZZZ",
"getUSB: Found multiple possible USB mount points, choosing the first one"
)
}
isUsbFound = possibleUSBStorageMounts.size != 0
if (PreferenceManager.getDefaultSharedPreferences(this)
.getString("pref_usb", "") == "" || !possibleUSBStorageMounts.contains(
PreferenceManager.getDefaultSharedPreferences(this)
.getString("pref_usb", "")
)
) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("pref_usb", possibleUSBStorageMounts[0])
.apply()
} else if (possibleUSBStorageMounts.size > 1) {
possibleUSBStorageMounts.forEach { usb ->
if (usb == PreferenceManager.getDefaultSharedPreferences(this)
.getString("pref_usb", "")
) {
possibleUSBStorageMounts[0] = usb
}
}
}
return possibleUSBStorageMounts[0]
}
Method for downloading videos
private fun downloadFromUrl(url : String){
if (manager == null) {
manager =
getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
}
if (url != "") {
val request = DownloadManager.Request(Uri.parse(url))
request.setDescription("")
request.setTitle("Download")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
val path = getUSB() + "/"
val dir = File(path, "Media")
if (!dir.exists()) {
dir.mkdir()
}
val file = File(dir, url.md5() + ".mp4")
val uri = Uri.fromFile(file)
request.setDestinationUri(uri)
}
My quest is, is it possible to download files directly to removable storage ? . If yes how it is?
Note : Now I can download files in Mi Android TV, but it is not possible in Sony Bravia Android TV(Access denied, can't write anything to usb).
Thanks in advance.