打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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.ResponseBodyimport 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.ResponseBodyimport 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的包名点开进入下载目录,可以看到文件已经被下载到指定的位置
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【Android Studio】图书管理系统——功能实现原理
Android 七种进度条的样式
自定义progressdialog
android – 在我更新到Retrofit 2.0之后,在不同的线程中发布了对onNext的onNext调用
一个小时打造新闻app
Android中使用Retrofit的五种请求方式案例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服