首页 > 解决方案 > 如何处理 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
getDownloadStatus816

标签: androidkotlinbroadcastreceiverandroid-download-manager

解决方案


此函数将返回下载状态。有关值,请参阅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; }    
 }

推荐阅读