Created
June 17, 2024 07:02
-
-
Save sajjadyousefnia/00512b7833ea4793c7997b2c88bad571 to your computer and use it in GitHub Desktop.
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
@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.getInt( | |
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES) | |
) | |
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) | |
withContext(Dispatchers.Main) { | |
runningDownloadList.first().downloadedBytes = bytesDownloaded.toLong() | |
runningDownloadList.first().percentage = progress | |
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