欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Android开发okhttp下载图片带进度

Android开发okhttp下载图片带进度

2025/2/21 5:17:22 来源:https://blog.csdn.net/u010074743/article/details/142464990  浏览:    关键词:Android开发okhttp下载图片带进度
Android开发okhttp下载图片带进度

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

一、思路:

用OkHttpClient().newCall(request)

二、效果图:

在这里插入图片描述

三、关键代码:
// 联系: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? = nullval buf = ByteArray(2048)var len: Int = -1var fos: FileOutputStream? = nulltry {inputStream = response.body?.byteStream()val total: Long = response.body?.contentLength()!!val file = File(getSandboxPath(mContext,fileType), fileName)fos = FileOutputStream(file)var sum: Long = 0while ((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 = itlistener(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结构图:

在这里插入图片描述有问题或者需要完整源码的私信我

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词