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

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

相关推荐
stevenzqzq21 分钟前
android lambda回调
android
林北北的霸霸3 小时前
django初识与安装
android·mysql·adb
Java 码农4 小时前
MySQL EXPLAIN 详解与优化指南
android·mysql·adb
stevenzqzq9 小时前
Android Hilt 入门教程_传统写法和Hilt写法的比较
android
wuwu_q9 小时前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
_李小白9 小时前
【Android FrameWork】第五天:init加载RC文件
android
2501_9160074710 小时前
手机使用过的痕迹能查到吗?完整查询指南与步骤
android·ios·智能手机·小程序·uni-app·iphone·webview
黄毛火烧雪下10 小时前
React Native (RN)项目在web、Android和IOS上运行
android·前端·react native
下位子11 小时前
『OpenGL学习滤镜相机』- Day7: FBO(帧缓冲对象)
android·opengl
從南走到北11 小时前
JAVA国际版同城外卖跑腿团购到店跑腿多合一APP系统源码支持Android+IOS+H5
android·java·ios·微信小程序·小程序