Last active
February 27, 2025 04:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[email protected]