println(“ n o w T i m e [ nowTime [ nowTime[{Thread.currentThread().name}] ${msg.joinToString(” “)}”)
}
/**
- 进度通用回调 不使用flow封装的话 使用这个
*/
internal typealias ProgressBlock = (state: DownloadState) -> Unit
/**
- 下载状态机
*/
sealed class DownloadState {
/**
- 未开始
*/
object UnStart : DownloadState()
/**
- 下载中
*/
class Progress(var totalNum: Long, var current: Long) : DownloadState()
/**
- 下载完成
*/
class Complete(val file: File?) : DownloadState()
/**
- 下载失败
*/
class Failure(val e: Throwable?) : DownloadState()
/**
- 下载失败
*/
class FileExistsNoDownload(val file: File?) : DownloadState()
}
fun downloadFile(url: String, destFileDirName: String, progressBlock: ProgressBlock) {
//下载状态 默认未开始
var state: DownloadState = DownloadState.UnStart
progressBlock(state)
// TODO: 2021/12/27 file 创建与判断可以封装
/**
- file 创建判断 可以封装
*/
val file = File(destFileDirName)
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
//文件存在 不需要下载
state = DownloadState.FileExistsNoDownload(file)
progressBlock(state)
return
} else {
file.createNewFile()
}
//下载
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
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}”)
is DownloadState.FileExistsNoDownload -> log(“已经存在 ${s.file?.absoluteFile}”)
is DownloadState.Progress -> log(“下载中 ${(s.current.toFloat() / s.totalNum) * 100}%”)
DownloadState.UnStart -> log(“下载未开始”)
}
}
对于上述封装使用起来没有问题,但是如果在android上面要把进度显示出来的话,就需要手动切换到UI线程了。不太方便。既然都用kotlin了,那么为什么不解除协程Flow封装呢?
所以,下面基于Flow的封装就来了。直接切换到Main线程,美滋滋。
知识储备:
/**
-
使用Flow改造文件下载
-
callbackFlow 可以保证线程的安全 底层是channel
*/
fun downloadFileUseFlow(url: String, destFileDirName: String) = callbackFlow {
var state: DownloadState = DownloadState.UnStart
send(state)
//获取文件对象
val file = File(destFileDirName).also { file ->
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
state = DownloadState.FileExistsNoDownload(file)
send(state)
//流关闭,返回
close()
return@callbackFlow
} else {
file.createNewFile()
}
}
//下载
val okHttpClient = OkHttpClient().newBuilder()
.dispatcher(dispatcher)
.writeTimeout(30, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.MINUTES)
.build()
val request = Request.Builder()
.url(url)
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
//更新状态
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
close()
}
override fun onResponse(call: Call, response: Response) {
//下载
val body = response.body
if (response.isSuccessful && body != null) {
//完整长度
val totalNum: Long = body.contentLength()
//当前下载的长度
var currentProgress: Long = 0L
var len = 0
response.use {
//等效于 FileOutputStream(file) 输出流
val outputStream = file.outputStream()
尾声
开发是需要一定的基础的,我是08年开始进入Android这行的,在这期间经历了Android的鼎盛时期,和所谓的Android”凉了“。中间当然也有着,不可说的心酸,看着身边朋友,同事一个个转前端,换行业,其实当时我的心也有过犹豫,但是我还是坚持下来了,这次的疫情就是一个好的机会,大浪淘沙,优胜劣汰。再等等,说不定下一个黄金浪潮就被你等到了。
- 330页 PDF Android核心笔记
- 几十套阿里 、字节跳动、腾讯、华为、美团等公司2020年的面试题
- PDF和思维脑图,包含知识脉络 + 诸多细节
- Android进阶系统学习视频
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!
Android核心笔记**
[外链图片转存中…(img-NyfUZKR3-1715679318790)]
- 几十套阿里 、字节跳动、腾讯、华为、美团等公司2020年的面试题
[外链图片转存中…(img-A0a7vPqh-1715679318793)]
[外链图片转存中…(img-0xlwnnIz-1715679318794)]
- PDF和思维脑图,包含知识脉络 + 诸多细节
[外链图片转存中…(img-BnRfa4qQ-1715679318796)]
- Android进阶系统学习视频
[外链图片转存中…(img-TAMJkSah-1715679318797)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!