The following code works perfectly to download mp3 file in external storage, but doens't work to download file in internal storage. A lot of smartphone doesn't have external storage. What can i do? I don't know how to implement async task in kotlin, if it is needed.
mywebView.setDownloadListener(object : DownloadListener {
override fun onDownloadStart(url: String, userAgent: String,
contentDisposition: String, mimetype: String,
contentLength: Long) {
val request = DownloadManager.Request(Uri.parse(url))
request.allowScanningByMediaScanner()
request.setDescription("Download file...")
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype))
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mimetype )
val webview = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
webview.enqueue(request)
Toast.makeText(getApplicationContext(), "Download avviato", Toast.LENGTH_LONG).show()
}
})
Cannot test the code at the moment, but it should be something like the follow:
mywebView.setDownloadListener(object : DownloadListener {
override fun onDownloadStart(url: String, userAgent: String,
contentDisposition: String, mimetype: String,
contentLength: Long) {
val request = DownloadManager.Request(Uri.parse(url))
request.allowScanningByMediaScanner()
request.setDescription("Download file...")
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype))
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory(), mimetype )
val webview = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
webview.enqueue(request)
Toast.makeText(getApplicationContext(), "Download avviato", Toast.LENGTH_LONG).show()
}
})
Related
How to set the Download manager time out and enable or disable the Download manager after 2 minutes.
fun downloadFile(url: String) {
val downloadManager = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadUri = Uri.parse(url)
val request = DownloadManager.Request(downloadUri).apply {
try {
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true)
.setTitle(url.substring(url.lastIndexOf("/") + 1))
// .setDescription("abc")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
url.substring(url.lastIndexOf("/") + 1)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
//TODO to get the Downloading status
val downloadId = downloadManager.enqueue(request)
val query = DownloadManager.Query().setFilterById(downloadId)
}
In above code how to handle the timeout with download manager.
You can schedule a new thread to run after x milliseconds using Handler.postDelayed(); In that scheduled thread you use would use DownloadManager.query to access the Cursor object which exposes the download status. If the download status indicates the download isn't completed successfully, you can cancel it using DownloadManager.remove()
I tested that this works:
private fun tryDownloadFileButCancelIfTimeout(url: String, millisecondsToTimeoutAfter : Long) {
val downloadManager = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadUri = Uri.parse(url)
val request = DownloadManager.Request(downloadUri).apply {
try {
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true)
.setTitle(url.substring(url.lastIndexOf("/") + 1))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
url.substring(url.lastIndexOf("/") + 1)
)
} catch (e: Exception) {
e.printStackTrace()
}
}
val downloadId = downloadManager.enqueue(request)
// Schedule a new thread that will cancel the download after millisecondsToTimeoutAfter milliseconds
Handler(Looper.getMainLooper()).postDelayed({
val downloadQuery = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(downloadQuery)
val downloadStatusColumn = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
cursor.moveToPosition(0)
val downloadStatus = cursor.getInt(downloadStatusColumn)
if (downloadStatus != DownloadManager.STATUS_SUCCESSFUL) {
downloadManager.remove(downloadId)
}
}, millisecondsToTimeoutAfter)
}
Posting the code I used to test (can import to Android Studio if you like, simple app with a single download button that starts the download and cancels in five seconds):
https://github.com/hishamhijjawi/DownloadCancelDemoStackOverflow
I am using Download Manager to Download PDFs and Images. Downloaded files are not getting saved in Download Folder. Here is my code.
`
val fileName = "MG Uploaded Documents"
val request = DownloadManager.Request(Uri.parse(downloadUrl))
.setTitle("Download")
.setDescription("Downloading")
request.setDestinationUri(
Uri.fromFile(File(this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
.toString() , fileName)))
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setAllowedOverMetered(true)
val dm = this.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
dm.enqueue(request)
this.T("File is Downloading. Please wait!")
`
This code is in Home Activity. Any help.
I was not saving the file name with .pdf extension.
Below is the working code.
private fun downloadPDF(url: String) {
val fileName = "YourPdfName.pdf"
val request = DownloadManager.Request(Uri.parse(url))
.setTitle("PDF Download")
.setDescription("Downloading")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setAllowedOverMetered(true)
// val dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
val dm = requireContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
dm.enqueue(request)
}
I am trying to download a pdf file from the server (I have the url), and I am trying this solution
fun downloadPDF(url: String?, fileName: String): ResponseStatus {
val uri = Uri.parse(url)
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager?
val request = DownloadManager.Request(uri)
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE
)
request.setTitle(fileName)
request.setDescription("Android Data download using DownloadManager.")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
request.setMimeType("*/*")
if (downloadManager == null) {
return ResponseStatus.Error( context.getString(R.string.download_error) )
}
downloadManager.enqueue(request)
return ResponseStatus.OK(uri)
}
this works for API 30 but not for API 27 and I don't know why.
Can someone help me please?
UPDATE:
I think that this can be a permissions problem because I tried again in API 27 and see this in the log java.lang.SecurityException: No permission to write to /storage/emulated/0/Download/file name12-34: Neither user 10080 nor current process has android.permission.WRITE_EXTERNAL_STORAGE.
I was able to solve the problem, I changed this line
request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS, fileName) for a uri that I parse with the address of the download folder and the file name, and I set it with request.setDestinationUri (destinationUri)
val destination = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() +
"/" + fileName
val destinationUri = Uri.parse("$FILE_BASE_PATH$destination")
I have audio 'url' "https://my-server.com/555.mp3"
how can I download it to "externalCacheDir" to be easy access without internet
i tried to use DownloadManager but i think there is better way to do it
fun downloadAudio(url:String){
val request = DownloadManager.Request(url.toUri())
val externalCachPath = getApplication<Application>().externalCacheDir!!.absolutePath
val fileName = "${UUID.randomUUID()}.3gp"
request.setDestinationInExternalPublicDir(externalCachPath,fileName)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
request.setDescription("Download")
request.setTitle(fileName)
download(request)
return filename
}
I cannot download the file using HTTPS(https://) transfer protocol.The file gets download while using Http(http://)
val request = DownloadManager.Request(
Uri.parse(url))
val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)
val destinationFile = File(
Environment.getExternalStorageDirectory().absolutePath + "/FileName",
fileName)
request.allowScanningByMediaScanner()
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.addRequestHeader("User-Agent", userAgent)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationUri(Uri.fromFile(destinationFile))
dm.enqueue(request)