state = DownloadState.Failure(e)
progressBlock(state)
}
override fun onResponse(call: Call, response: Response) {
response.use { res ->
//完整长度
var totalLength = 0L
//写入字节
val bytes = ByteArray(2048)
val fileOutputStream = FileOutputStream(file)
res.body?.also { responseBody ->
totalLength = responseBody.contentLength()
}?.byteStream()?.let { inputStream ->
try {
var currentProgress = 0L
var len = 0
state = DownloadState.Progress(totalLength, currentProgress)
do {
if (len != 0) {
currentProgress += len
fileOutputStream.write(bytes)
}
//状态改变
(state as DownloadState.Progress).current = currentProgress
progressBlock(state)
len = inputStream.read(bytes, 0, bytes.size)
} while (len != -1)
//状态改变完成
state = DownloadState.Complete(file)
progressBlock(state)
} catch (e: Exception) {
state = DownloadState.Failure(e)
progressBlock(state)
} finally {
inputStream.close()
fileOutputStream.close()
}
}
}
}
})
}
使用
downloadFile(
“https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe”,
“download/WeChatSetup.exe”
) { state: DownloadState ->
when (val s = state) {
is DownloadState.Complete -> log(“下载完成 文件路径为 ${s.file?.absoluteFile}”)
is DownloadState.Failure -> log(“下载失败 ${s.e?.message}”)</