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

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

相关推荐
小书房24 分钟前
Kotlin的by
android·开发语言·kotlin·委托·by
jinanwuhuaguo1 小时前
(第二十八篇)OpenClaw成本与感知的奇点——从“Token封建制”到“全民养虾”的本体论地基
android·人工智能·kotlin·拓扑学·openclaw
xxjj998a2 小时前
Laravel4.x核心特性全解析
android·mysql·laravel
JoshRen2 小时前
2026教程:在Android Termux中集成Gemini 3镜像站实现移动端文档自动处理与摘要生成(附国内免费方案)
android
诸神黄昏EX3 小时前
Android Google KEY
android
一起搞IT吧3 小时前
Android性能系列专题理论之十一:block IO问题分析思路
android·嵌入式硬件·智能手机·性能优化
小妖6664 小时前
怎么用 tauri 创建编译 android 应用程序
android·tauri
鸟儿不吃草5 小时前
安卓实现左右布局聊天界面
android·开发语言·python
xxjj998a6 小时前
Laravel 1.x:PHP框架的原始魅力
android·php·laravel
formula100006 小时前
在iOS/安卓上远程连接任何 Agent!Claude、Codex、Copilot、Gemini、OpenCode 等
android·copilot