Created
May 9, 2021 14:06
-
-
Save shibbirweb/ab7126e83a7101763d84f53ac55f638d to your computer and use it in GitHub Desktop.
Android - Downlaod Progress - Download manager download progress tracker
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
import android.app.Application | |
import android.app.DownloadManager | |
import android.content.Context | |
import androidx.lifecycle.LiveData | |
import kotlinx.coroutines.* | |
import kotlin.coroutines.CoroutineContext | |
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)) | |
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(1000) | |
} | |
} | |
} | |
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