Skip to content

Instantly share code, notes, and snippets.

@staakk
Created October 18, 2017 12:34
Show Gist options
  • Save staakk/b1d82e4d26dfb6a19b67083a0d4575ea to your computer and use it in GitHub Desktop.
Save staakk/b1d82e4d26dfb6a19b67083a0d4575ea to your computer and use it in GitHub Desktop.
import java.io.*
class FileDownloader(
val onProgressUpdate: ((fileSize: Long, downloadedSize: Long) -> Unit)?,
val onDownloadComplete: () -> Unit) {
var bufferSize = 1024 * 8
var singleReadSize = 1024 * 4
var progressNotificationDelay = 1000
fun startDownload(contentLength: Long, byteStream: InputStream, outputStream: OutputStream) {
val data = ByteArray(singleReadSize)
val bis = BufferedInputStream(byteStream, bufferSize)
var total: Long = 0
val startTime = System.currentTimeMillis()
var timeCount = 1
var count = bis.read(data)
while (count != -1) {
total += count.toLong()
val currentTime = System.currentTimeMillis() - startTime
if (currentTime > progressNotificationDelay * timeCount) {
onProgressUpdate?.let { it(contentLength, total) }
timeCount++
}
outputStream.write(data, 0, count)
count = bis.read(data)
}
onDownloadComplete()
outputStream.flush()
outputStream.close()
bis.close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment