如何处理下载管理器的不同结果

How to hande different results of DownloadManager

我需要做的事情:
URL使用DownloadManager下载文件,分别处理下载成功和下载错误。
我尝试了什么:
我使用 BroadcastReceiver 来捕获文件下载的结果。我尝试使用 DownloadManager.ACTION_DOWNLOAD_COMPLETE 作为标记,但它不仅在成功下载文件时触发,而且在发生错误且未下载文件时触发。
因此,似乎 DownloadManager.ACTION_DOWNLOAD_COMPLETE 只报告尝试下载,无论结果如何。 有没有办法只捕获成功的下载?
我的代码:
fragment.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 returns 成功时 8 的整数,失败时 16 的整数,我可以进一步处理。

这个函数会return下载状态。有关值,请参阅 DownloadManager。如果找不到给定 ID 的下载,它 returns -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; }    
 }