android studio Android 使用Retrofit+协程实现超简单大文件下载并回显进度条 - android:layout_height=&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力 👁️ 585 次阅读

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

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

android:shape="rectangle">

创建alert_dialog_download_progress.xml布局

android:layout_width="500dp"

android:layout_height="240dp"

android:padding="20dp"

android:orientation="vertical"

android:gravity="center"

android:background="@drawable/progress_dialog_bg_style">

android:id="@+id/d_title"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:textSize="30sp"

android:layout_marginBottom="50dp"

android:text="标题" />

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"/>

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

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(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(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()

}

}

)

)

}

别忘了加上网络请求权限

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

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

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧