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结构图:

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

相关推荐
爱勇宝10 小时前
我做了一个只用来搜歌词的小 App
android·前端·后端
众少成多积小致巨13 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
Coffeeee20 小时前
如何使用Glide和Coil加载WebP动图
android·kotlin·glide
Kapaseker20 小时前
5 分钟搞懂 Kotlin DSL
android·kotlin
恋猫de小郭21 小时前
AI Agent 开发究竟是啥?如何用 AI 开发 Agent ?深入浅出给你一套概念
android·前端·ai编程
黄林晴21 小时前
Android 17 正式发布!target 37 一大批旧代码直接不能用了
android
Carson带你学Android21 小时前
Android 17 正式发布:AI 终于成了系统能力
android·前端·ai编程
三少爷的鞋1 天前
当 UseCase 开始长期监听,它可能已经不是 UseCase 了
android
恋猫de小郭1 天前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划
android·前端·flutter
恋猫de小郭1 天前
解读 Android 17 全新内存限制,有没有“豁免”后门?
android·前端·flutter