热点新闻
Android 使用Retrofit+协程实现超简单大文件下载并回显进度条
2023-07-13 07:22  浏览:1113  搜索引擎搜索“手机速企网”
温馨提示:信息一旦丢失不一定找得到,请务必收藏信息以备急用!本站所有信息均是注册会员发布如遇到侵权请联系文章中的联系方式或客服删除!
联系我时,请说明是在手机速企网看到的信息,谢谢。
展会发布 展会网站大全 报名观展合作 软文发布

这里直接使用之前文章配置好的傻瓜式网络请求工具来写文件下载,不对Retrofit做过多描述,不清楚的可以看这篇文章<<Android 使用Retrofit+协程+函数式接口实现傻瓜式接口请求>> ,废话不多说,直接上代码

安卓自带的进度条弹窗过时了,这里简单创建一个进度条弹窗

drawable文件夹创建progress_dialog_bg_style.xml一个圆角白色背景样式

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="10dp"/> <solid android:color="@color/white" /> </shape>

创建alert_dialog_download_progress.xml布局

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="500dp" android:layout_height="240dp" android:padding="20dp" android:orientation="vertical" android:gravity="center" android:background="@drawable/progress_dialog_bg_style"> <TextView android:id="@+id/d_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="30sp" android:layout_marginBottom="50dp" android:text="标题" /> <ProgressBar android:id="@+id/d_progress_bar" style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:layout_width="match_parent" android:max="100" android:layout_height="wrap_content"/> </LinearLayout>

创建弹窗工具类,使用刚才创建好的布局

object DialogUtil { fun showDownloadProgress( context: Context, title: String? = null ): alertDialog = context.let { alertDialog.Builder(it).create().apply { // 设置点击dialog的外部能否取消弹窗 setCanceledonTouchOutside(false) // 设置能不能返回键取消弹窗 setCancelable(false) show() window?.run { setLayout( 600, 200 ) } setContentView( View.inflate(it, R.layout.alert_dialog_download_progress, null).apply { // 设置成顶层视图 bringToFront() title?.let { text -> findViewById<TextView>(R.id.d_title).text = text } } ) } } }

简单封装一个下载工具类

先定义一个下载参数实体DownloadDTO

import okhttp3.ResponseBody import java.io.File data class DownloadDTO ( val filename: String, val filepath: String, val body: ResponseBody, val callback: DownloadCallback ) { // 下载回调接口,用来返回下载情况 interface DownloadCallback { fun onSuccess(file: File) fun onProgress(progress: Int) fun onFailure(e: Exception) } }

编写下载工具类DownloadFileUtil,用到了挂起函数必须在协程中使用

object DownloadFileUtil { suspend fun download(dto: DownloadDTO) = coroutineScope { async(Dispatchers.IO) { try { val filepath = File(dto.filepath) if (!filepath.exists()) { filepath.mkdirs() } val file = File(filepath.canonicalPath, dto.filename) if (file.exists()) { file.delete() } try { val buffer = ByteArray(1024) val contentLength: Long = dto.body.contentLength() var lastProgress = 0 dto.body.byteStream().use { input -> FileOutputStream(file).use { fos -> var length: Int var sum: Long = 0 while (input.read(buffer).also { length = it } != -1) { fos.write(buffer, 0, length) sum += length.toLong() val progress = (sum * 100 / contentLength).toInt() if (progress > lastProgress) { lastProgress = progress dto.callback.onProgress(progress) } } fos.flush() } } dto.callback.onSuccess(file) LogUtil.yd("DownloadFileUtil.download filepath: ${file.path}") } catch (e: Exception) { if (file.exists()) { file.delete() } dto.callback.onFailure(e) } } catch (e: Exception) { dto.callback.onFailure(e) } } }.await() }

开始使用写好的工具来下载文件

在ApiService 中添加下载接口

import okhttp3.ResponseBody import retrofit2.http.* interface ApiService { @Streaming @GET suspend fun downloadFile(@Url fileUrl: String): ResponseBody }

编写具体调用下载接口的代码

// 开头说的文章有HttpRequest的封装过程 HttpRequest.executeAsync { // 开始请求,这里链接用的是自己服务器上的就不放出来了 val downloadFile = it.downloadFile("http://xxxx/xxx.rar") // 显示进度条弹窗 val dialog = DialogUtil.showDownloadProgress(this@MainActivity, "正在下载...") val view = dialog.findViewById<ProgressBar>(R.id.d_progress_bar) delay(500) // 下载并返回进度 DownloadFileUtil.download( DownloadDTO( "文件名.rar", // 下载保存路径 "${applicationContext.filesDir.absolutePath}${File.separator}test${File.separator}", downloadFile, object : DownloadDTO.DownloadCallback { override fun onSuccess(file: File) { // 下载完成 dialog.cancel() } override fun onProgress(progress: Int) { // 更新下载进度 view.progress = progress } override fun onFailure(e: Exception) { // 下载失败 dialog.cancel() e.printStackTrace() } } ) ) }

别忘了加上网络请求权限

<uses-permission android:name="android.permission.INTERNET" />

启动代码开始下载文件







可以看到已经在下载了,下载完成后可以如图打开目录







找到自己APP的包名点开进入下载目录,可以看到文件已经被下载到指定的位置







发布人:e6dc****    IP:117.173.23.***     举报/删稿
展会推荐
让朕来说2句
评论
收藏
点赞
转发