I am trying to download a file using Android's DownloadManager and trying to print the download tho the console using log statements. Though the file is downloaded properly, i am not able to see the log statement of download's progress Here is my code
private fun downloadPdf(fileName: String?, fileExtension: String?, destinationDirectory: String?, url: String?) {
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(destinationDirectory, fileName + fileExtension)
val downloadId = downloadManager.enqueue(request)
thread {
val query = DownloadManager.Query()
query.setFilterById(downloadId)
val cursor = downloadManager.query(query)
if(cursor.moveToFirst()){
val sizeIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
val downloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
val size = cursor.getInt(sizeIndex)
val downloaded = cursor.getInt(downloadedIndex)
val progress: Long
if(size != -1){
progress = downloaded * 100L / size
runOnUiThread {
Log.i("pritishsawantprogress",progress.toString())
}
}
}
}
}
Any help would be greatly appreciated
private fun downloadPdf(fileName: String?, fileExtension: String?, destinationDirectory: String?, url: String?) {
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(destinationDirectory, fileName + fileExtension)
val downloadId = downloadManager.enqueue(request)
thread {
var downloading = true
while (downloading){
val query = DownloadManager.Query()
query.setFilterById(downloadId)
val cursor = downloadManager.query(query)
if(cursor.moveToFirst()){
val bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
val bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
if(cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL){
downloading = false
}
val progress = ((bytesDownloaded * 100L)/bytesTotal).toInt()
runOnUiThread {
Log.i("pritishsawantprogress",progress.toString())
}
cursor.close()
}
}
}
}