Created
June 16, 2024 17:24
-
-
Save sajjadyousefnia/fc459dce2986e223784685c01f1b118b 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
| val request = DownloadManager.Request(Uri.parse(url)) | |
| .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) | |
| .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "filename.ext") | |
| .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) | |
| val manager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager | |
| val downloadId = manager.enqueue(request) | |
| val query = DownloadManager.Query().setFilterById(downloadId) | |
| var isDownloading = true | |
| while (isDownloading) { | |
| val cursor = manager.query(query) | |
| if (cursor.moveToFirst()) { | |
| val bytesDownloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)) | |
| val bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)) | |
| if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) { | |
| isDownloading = false | |
| } | |
| if (bytesTotal > 0) { | |
| val progress = (bytesDownloaded * 100L / bytesTotal).toInt() | |
| listener?.onProgress(progress) | |
| } | |
| } | |
| cursor.close() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment