android - 如何处理 DownloadManager 的不同结果
问题描述
我需要做的:
使用 URL 通过 URL 下载文件DownloadManager
,并分别处理成功下载和错误下载。
我尝试了什么:
我曾经BroadcastReceiver
捕获文件下载的结果。我尝试将其DownloadManager.ACTION_DOWNLOAD_COMPLETE
用作标记,但它不仅会在文件成功下载时触发,而且还会在发生错误且未下载文件时触发。因此,无论结果如何
,似乎都只报告了尝试下载。有没有办法只捕获成功的下载?
我的代码:
fragment.ktDownloadManager.ACTION_DOWNLOAD_COMPLETE
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
解决方案
此函数将返回下载状态。有关值,请参阅DownloadManager。如果未找到给定 id 的下载,则返回 -1。
int getDownloadStatus(long id) {
try {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);
if (cursor.getCount() == 0) return -1;
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
} catch(Exception ex) { return -1; }
}
推荐阅读
- windows - 如何使继承的 AUTOLOAD 用于非方法工作?
- moodle - 如何为 Moodle Mobile 应用程序扩展 Moodle 插件
- javascript - Discord JS,回复某个用户ID
- javascript - 从电子表格中搜索数据并使用 google web app 脚本以 html 形式显示
- javascript - 如何在 Progressive Web Apps 中的浏览器内存储离线存储永久数据?
- git - 如何使下一个 git 提交准确地代表另一个提交的项目状态而不合并?
- node.js - Node.js Twitter Bot 返回错误:错误的 Twitter 流请求:410
- react-native - 导航到一个屏幕 tp 另一个
- sql - 尝试编写查询以获取帖子和相关附件的列表
- android - 根据 Android 设备中的 AdMob,这可以接受吗?