OkHttp初探2:如何使用OkHttp进行下载封装?带进度条?Kotlin+Flow版本。,2024最新腾讯Android高级面试题总结

本文介绍了如何使用Kotlin和Flow来封装OkHttp进行文件下载,并实时显示进度。通过创建CallbackFlow确保线程安全,利用Dispatcher在主线程更新UI,简化Android应用的下载操作。
摘要由CSDN通过智能技术生成

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}”)</

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值