Android开发okhttp下载图片带进度

Android开发okhttp下载图片带进度

下载网络图片的方法有很多,这次介绍写用okhttp来下载网络图片,主要我看中的是用okhttp下载有进度返回,提示下用户

一、思路:

用OkHttpClient().newCall(request)

二、效果图:
三、关键代码:
kotlin 复制代码
// 联系:893151960
fun download(mContext: Context,url: String,fileName:String,fileType:String, listener:(Int, Int,String) -> Unit) {
        // 需要token的时候可以这样做
        // Request request = new Request.Builder().header("token",token).url(url).build();
        val request: Request = Request.Builder().url(url).build()

        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
                listener(0,2,"")
            }

            override fun onResponse(call: Call, response: Response) {
                listener(0,3,"")
                var inputStream: InputStream? = null
                val buf = ByteArray(2048)
                var len: Int = -1
                var fos: FileOutputStream? = null
                try {
                    inputStream = response.body?.byteStream()
                    val total: Long = response.body?.contentLength()!!
                    val file = File(getSandboxPath(mContext,fileType), fileName)
                    fos = FileOutputStream(file)
                    var sum: Long = 0
                    while ((inputStream?.read(buf) ?: -1).also { len = it } != -1) {
                        fos.write(buf, 0, len)
                        sum += len.toLong()
                        (sum * 1.0f / total * 100).toInt().let {
                            if(it > progress){
                                progress = it
                                listener(it,0,"")
                            }
                        }
                    }
                    fos.flush()
                    listener(0,1,file.path)
                } catch (e: Exception) {
                    listener(0,2,"")
                } finally {
                    try {
                        inputStream?.close()
                        fos?.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }
四、完整项目demo结构图:

有问题或者需要完整源码的私信我

相关推荐
bqliang1 小时前
Compose 实验性 Styles API
android·android jetpack
大尚来也1 小时前
PHP 入门指南:从零基础到掌握核心语法
android
summerkissyou19871 小时前
android -wifi/蓝牙-常见面试题
android·wifi·bluetooth
XiaoLeisj1 小时前
Android Activity 页面导航基础:Manifest 声明、Intent 显式/隐式跳转与数据传递
android·java
littlegnal2 小时前
Flutter Android如何延迟加载代码
android·flutter
秋氘渔2 小时前
MySQL EXPLAIN实战:6种索引失效场景验证与优化
android·数据库·mysql·索引
钟睿2 小时前
HarmonyOS花瓣地图自定义点聚合功能
android·harmonyos·arkts
三少爷的鞋2 小时前
Android 协程时代,出现 ReentrantLock 就是架构警报
android
诸神黄昏EX2 小时前
seccomp策略
android
JiaoJunfeng2 小时前
Android AI开发 工具选择
android·ai 开发