Skip to content

Instantly share code, notes, and snippets.

@onyxmueller
Last active September 22, 2023 15:14
Show Gist options
  • Save onyxmueller/8b82679daa43fc70efe5b3978b591bd9 to your computer and use it in GitHub Desktop.
Save onyxmueller/8b82679daa43fc70efe5b3978b591bd9 to your computer and use it in GitHub Desktop.
An Android Kotlin class to track and update download progress by the DownloadManager.
/**
* Tracks download of a DownloadManager job and reports progress.
*/
internal class DownloadProgressUpdater(private val manager: DownloadManager, private val downloadId: Long, private var downloadProgressListener: DownloadProgressListener?) : Thread() {
private val query: DownloadManager.Query = DownloadManager.Query()
private var totalBytes: Int = 0
interface DownloadProgressListener {
fun updateProgress(progress: Long)
}
init {
query.setFilterById(this.downloadId)
}
override fun run() {
while (downloadId > 0) {
Thread.sleep(250)
manager.query(query).use {
if (it.moveToFirst()) {
//get total bytes of the file
if (totalBytes <= 0) {
totalBytes = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
}
val downloadStatus = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_STATUS))
val bytesDownloadedSoFar = it.getInt(it.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
if (downloadStatus == DownloadManager.STATUS_SUCCESSFUL || downloadStatus == DownloadManager.STATUS_FAILED) {
this.interrupt()
} else {
//update progress
val percentProgress = ((bytesDownloadedSoFar * 100L) / totalBytes)
Timber.d("Download progress: $percentProgress")
downloadProgressListener?.updateProgress(percentProgress)
}
}
}
}
if (downloadProgressListener != null) {
downloadProgressListener = null
}
}
}
@AdminIT-arch
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment