Android 使用Retrofit+协程实现超简单大文件下载并回显进度条

这里直接使用之前文章配置好的傻瓜式网络请求工具来写文件下载,不对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的包名点开进入下载目录,可以看到文件已经被下载到指定的位置


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容