Forked from FhdAlotaibi/DownloadProgressLiveData.kt
Created
February 18, 2022 16:18
-
-
Save ricardopereira/b47ba39872aa399f3ad7c2390434b0ab to your computer and use it in GitHub Desktop.
Observe Download manager progress using LiveData and Coroutine
This file contains hidden or 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
data class DownloadItem(val bytesDownloadedSoFar: Long = -1, val totalSizeBytes: Long = -1, val status: Int) | |
class DownloadProgressLiveData(private val application: Application, private val requestId: Long) : LiveData<DownloadItem>(), CoroutineScope { | |
private val downloadManager by lazy { | |
application.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager | |
} | |
private val job = Job() | |
override val coroutineContext: CoroutineContext | |
get() = Dispatchers.IO + job | |
override fun onActive() { | |
super.onActive() | |
launch { | |
while (isActive) { | |
val query = DownloadManager.Query().setFilterById(requestId) | |
val cursor = downloadManager.query(query) | |
if (cursor.moveToFirst()) { | |
val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) | |
Timber.d("Status $status") | |
when (status) { | |
DownloadManager.STATUS_SUCCESSFUL, | |
DownloadManager.STATUS_PENDING, | |
DownloadManager.STATUS_FAILED, | |
DownloadManager.STATUS_PAUSED -> postValue(DownloadItem(status = status)) | |
else -> { | |
val bytesDownloadedSoFar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)) | |
val totalSizeBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)) | |
postValue(DownloadItem(bytesDownloadedSoFar.toLong(), totalSizeBytes.toLong(), status)) | |
} | |
} | |
if (status == DownloadManager.STATUS_SUCCESSFUL || status == DownloadManager.STATUS_FAILED) | |
cancel() | |
} else { | |
postValue(DownloadItem(status = DownloadManager.STATUS_FAILED)) | |
cancel() | |
} | |
cursor.close() | |
delay(300) | |
} | |
} | |
} | |
override fun onInactive() { | |
super.onInactive() | |
job.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment