Created
October 18, 2017 12:34
-
-
Save staakk/b1d82e4d26dfb6a19b67083a0d4575ea 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
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