Skip to content

Instantly share code, notes, and snippets.

@sajjadyousefnia
Created June 17, 2024 09:45
Show Gist options
  • Save sajjadyousefnia/6369990ad8f62ef188ac5bca29db075e to your computer and use it in GitHub Desktop.
Save sajjadyousefnia/6369990ad8f62ef188ac5bca29db075e to your computer and use it in GitHub Desktop.
@SuppressLint("Range")
private suspend fun downloadFromScratch() {
try {
val downloadManager = getSystemService(DownloadManager::class.java)
val request = DownloadManager.Request(currentUrl.toUri()).setMimeType("video/*")
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI and DownloadManager.Request.NETWORK_MOBILE)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setTitle("در حال دانلود فیلم " + currentTitle).setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, DOWNLOADS_SUB_DIRECTORY + currentTitle
)
val downloadId = downloadManager.enqueue(request)
val query = DownloadManager.Query().setFilterById(downloadId)
var isDownloading = true
val downloadModel = DownloadModel(
title = currentTitle,
fileName = currentTitle,
url = currentUrl,
downloadedBytes = 0,
downloadId = downloadId,
directory = Environment.DIRECTORY_DOWNLOADS + DOWNLOADS_SUB_DIRECTORY + currentTitle,
percentage = 0,
startDateTime = getCurrentDateTime()
)
runningDownloadList.add(
downloadModel
)
db.appDao().insertNewDownload(downloadModel)
withContext(Dispatchers.Main) {
runningAdapter.notifyDataSetChanged()
}
while (isDownloading) {
val cursor = downloadManager.query(query)
if (cursor.moveToFirst()) {
val bytesDownloaded = cursor.getLong(
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
)
val bytesTotal = cursor.getLong(
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
)
// if (downloadModel.totalBytes == 0L) {
downloadModel.totalBytes = bytesTotal
// }
val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
if (status == DownloadManager.STATUS_SUCCESSFUL) {
isDownloading = false
} else if (status == DownloadManager.STATUS_FAILED) {
val reason =
cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON))
// listener?.onFailed("Download failed: $reason")
}
if (bytesTotal > 0) {
val progress = (bytesDownloaded * 100L / bytesTotal).toInt()
db.appDao().updatePercentageDownload(downloadId, bytesDownloaded, progress)
val downloadItem = runningDownloadList.first()
downloadItem.downloadedBytes = bytesDownloaded.toLong()
downloadItem.percentage = progress
val speed = calculateDownloadSpeed(cursor)
if (speed != "_" && speed != "0") {
downloadItem.currentSpeed = speed
}
if (bytesDownloaded == bytesTotal) {
downloadItem.isComplete = 1
}
withContext(Dispatchers.Main) {
runningAdapter.notifyDataSetChanged()
}
// listener?.onProgress(progress)
}
}
cursor.close()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment