gpt4 book ai didi

android - 如何从Android中的URL下载文件?

转载 作者:行者123 更新时间:2023-12-02 12:40:06 25 4
gpt4 key购买 nike

从 url 下载文件的最佳方法是什么?我尝试使用下载管理器。但我不明白如何获取下载文件的 Uri 。这是我的代码:

   file?.let {
val uri = Uri.parse(it)
val downloadManager = getSystemService<Any>(Context.DOWNLOAD_SERVICE) as DownloadManager?
val request = DownloadManager.Request(uri)
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or
DownloadManager.Request.NETWORK_MOBILE)
request.allowScanningByMediaScanner()
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "downloadfileName")
request.setMimeType("*/*")
downloadManager?.enqueue(request)
}
也许今天有更好的方法来下载文件并获取 Uri。请帮我

最佳答案

How to download file from Url

fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")

if (!direct.exists()) {
direct.mkdirs()
}
val extension = url?.substring(url.lastIndexOf("."))
val downloadReference: Long
var dm: DownloadManager
dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(url)
val request = DownloadManager.Request(uri)
request.setDestinationInExternalPublicDir(
"/your_folder",
"pdf" + System.currentTimeMillis() + extension
)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setTitle(title)
Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()

downloadReference = dm?.enqueue(request) ?: 0

return downloadReference

}
在调用此方法之前,请检查运行时权限:
Manifest.permission.WRITE_EXTERNAL_STORAGE

关于android - 如何从Android中的URL下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63099515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com