【发布时间】:2020-09-01 18:05:26
【问题描述】:
我需要做什么:
通过 URL 使用DownloadManager 下载文件,并分别处理成功下载和错误下载。
我尝试了什么:
我使用BroadcastReceiver 来捕获文件下载的结果。我尝试使用DownloadManager.ACTION_DOWNLOAD_COMPLETE 作为标记,但它不仅会在成功下载文件时触发,而且还会在发生错误且未下载文件时触发。
因此,DownloadManager.ACTION_DOWNLOAD_COMPLETE 似乎只报告了无论结果如何都尝试下载。
有没有办法只捕获成功的下载?
我的代码:
片段.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
downloadCompleteReceiver = object : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
Snackbar.make(requireActivity().findViewById(android.R.id.content), getString(R.string.alert_files_successfully_downloaded), Snackbar.LENGTH_LONG).show()
}
}
val filter = IntentFilter()
filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
requireActivity().registerReceiver(downloadCompleteReceiver, filter)
}
请求:
fun downloadMediaFiles(listOfUrls: List<MediaDto>, activity: Activity, authToken:String) {
if (isPermissionStorageProvided(activity)) {
val manager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
listOfUrls.forEach {
val request = DownloadManager.Request(Uri.parse(it.url))
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setTitle(activity.getString(R.string.download_manager_title))
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(
getDestinationDirectoryFromFileExtension(it.url),
"${System.currentTimeMillis()}"
)
request.addRequestHeader("authorization", authToken)
manager.enqueue(request)
}
}
}
已解决
Rediska 写的内容 + 还需要将此添加到我的 BroadcastReceiver 对象中:
val referenceId = intent!!.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, -1L
)
然后将此referenceId 作为参数传递给getDownloadStatus。getDownloadStatus 在成功时返回整数8,如果失败则返回16,我可以进一步处理。
【问题讨论】:
标签: android kotlin broadcastreceiver android-download-manager