這里直接使用之前文章配置好的傻瓜式網絡請求工具來寫文件下載,不對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的包名點開進入下載目錄,可以看到文件已經被下載到指定的位置