从url下载文件的最佳方法是什么。我尝试使用DownloadManager。但是我不明白如何获取下载文件的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。请帮我 最佳答案
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