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()
//输入流
val byteStream = body.byteStream()
try {
val bates = ByteArray(2048)
//设置状态对象拉出来,避免循环一直创建对象
state = DownloadState.Progress(totalNum, currentProgress)
//循环读写
do {
if (len != 0) {
currentProgress += len
outputStream.write(bates)
}
//更新进度
(state as DownloadState.Progress).current = currentProgress
this@callbackFlow.trySendBlocking(state)
len = byteStream.read(bates, 0, bates.size)
} while (len != -1)
//下载完成
state = DownloadState.Complete(file)
this@callbackFlow.trySendBlocking(state)
} catch (e: Exception) {
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
} finally {
outputStream.close()
byteStream.close()
//关闭callbackFlow
this@callbackFlow.close()
}
}
} else {
//更新状态且关闭
state = DownloadState.Failure(Exception(response.message))
this@callbackFlow.trySendBlocking(state)
close()
}
}
})
//使用channelFlow 必须使用awaitClose 挂起flow等待channel结束
awaitClose {
log(“callbackFlow关闭 .”)
}
}
.buffer(Channel.CONFLATED) //设置 立即使用最新值 buffer里面会调用到fuse函数,继而调用到create函数重新创建channelFlow
.flowOn(Dispatchers.Default) //直接设置callbackFlow执行在异步线程
.catch { e ->
//异常捕获重新发射
emit(DownloadState.Failure(e))
}
使用
//这里使用runBlocking只是为了跑程序,一般和lifecycleScope等合作使用
runBlocking(Dispatchers.Main) {
downloadFileUseFlow(
“https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe”,
“download/WeChatSetup.exe”
).onEach { downloadState ->
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
学习福利
【Android 详细知识点思维脑图(技能树)】
其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。
虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。这只能说明 Android 中级以下的岗位饱和了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。
这里附上上述的面试题相关的几十套字节跳动,京东,小米,腾讯、头条、阿里、美团等公司19年的面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。
由于篇幅有限,这里以图片的形式给大家展示一小部分。
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。
这里附上上述的面试题相关的几十套字节跳动,京东,小米,腾讯、头条、阿里、美团等公司19年的面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。
由于篇幅有限,这里以图片的形式给大家展示一小部分。
[外链图片转存中…(img-CEbEgRIw-1712292601048)]
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。