wangrong
2024-12-12 e2e72aa8809a0bfa8d24ac0048a138d3d56c9781
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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()
            }
    }
}