package com.shsening.autouploadvideos.utils
|
|
import android.app.DownloadManager
|
import android.content.Context
|
import android.net.Uri
|
import android.os.Environment
|
import android.widget.Toast
|
import java.io.File
|
|
class DownloadHelper(private val context: Context) {
|
|
private val downloadManager =
|
context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
|
|
fun downloadSingleFile(fileUrl:String,fileUri:File) {
|
try {
|
if (fileUri.exists()) {
|
return
|
}
|
// 确保目标文件所在的目录存在
|
val parentDir = fileUri.parentFile
|
if (parentDir != null && !parentDir.exists()) {
|
parentDir.mkdirs() // 创建目录
|
}
|
val request = DownloadManager.Request(Uri.parse(fileUrl)).apply {
|
setTitle("Downloading ${fileUri.name}")
|
setDescription("Downloading file...")
|
.setDestinationUri(Uri.fromFile(fileUri)) // 设置下载文件保存路径
|
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
|
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
|
|
}
|
// 将下载请求加入队列
|
downloadManager.enqueue(request)
|
|
} catch (e: Exception) {
|
e.printStackTrace()
|
Toast.makeText(context, "Failed to download: $fileUrl", Toast.LENGTH_SHORT).show()
|
}
|
}
|
}
|