【发布时间】:2021-10-04 00:38:28
【问题描述】:
我正在调用下面的函数来下载二进制文件。
fun downloadFile(
baseActivity: Context,
batteryId: String,
downloadFileUrl: String?,
title: String?
): Long {
val directory =
File(Environment.getExternalStorageDirectory().toString() + "/destination_folder")
if (!directory.exists()) {
directory.mkdirs()
}
//Getting file extension i.e. .bin, .mp4 , .jpg, .png etc..
val fileExtension = downloadFileUrl?.substring(downloadFileUrl.lastIndexOf("."))
val downloadReference: Long
var objDownloadManager: DownloadManager =
baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(downloadFileUrl)
val request = DownloadManager.Request(uri)
//Firmware file name as batteryId and extension
firmwareFileSubPath = batteryId + fileExtension
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
"" + batteryId + fileExtension
)
request.setTitle(title)
downloadReference = objDownloadManager.enqueue(request) ?: 0
return downloadReference
}
文件下载后,我会在下面的 onReceive() 广播接收器方法中接收它:
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
intent.extras?.let {
//retrieving the file
val downloadedFileId = it.getLong(DownloadManager.EXTRA_DOWNLOAD_ID)
val downloadManager =
getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri: Uri = downloadManager.getUriForDownloadedFile(downloadedFileId)
viewModel.updateFirmwareFilePathToFirmwareTable(uri)
}
}
}
我正在一个一个下载文件,想知道下载的是哪个文件。 根据特定的文件下载,我必须更新本地数据库中的条目。
那么,在 onReceive() 方法中,我如何识别下载的是哪个特定文件?
谢谢。
【问题讨论】:
-
if(!directory.mkdirs()) 返回;也显示一个 toast 来通知用户。
-
你有一个 uri 并定义了文件。没有人需要更多。你为什么要?你有源文件的下载参考。
-
@blackapps 如何查看?请详细说明。
-
识别下载的一种方法是,当您将下载排入队列时,它会返回您在整个系统中唯一的 ID。因此,当您调用此代码时,您需要将该 ID 保存在某处:
objDownloadManager.enqueue(request),然后在接收方法上,您可以使用该 ID 进行比较以识别您的下载。
标签: android file kotlin android-download-manager download-manager