在 Android 中使用下载管理器下载后识别特定文件

Identifying the particular file after downloaded using Download Manager in Android

我正在调用下面的函数来下载二进制文件。

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() 方法中,我如何识别下载了哪个特定文件?

谢谢。

你有文件Uri,现在简单的获取文件名来识别文件,你可以使用下面的函数来获取文件名

fun getFileName(uri: Uri): String?  {
    var result: String? = null
    when(uri.scheme){
        "content" -> {
             val cursor: Cursor? = getContentResolver().query(uri, null, null, null, null)
             cursor.use {
                 if (it != null && it.moveToFirst()) {
                     result = it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                 }
             }
        }
        else -> {
            val lastSlashIndex = uri.path?.lastIndexOf('/')
            if(lastSlashIndex != null && lastSlashIndex != -1) {
                 result = uri.path!!.substring(lastSlashIndex + 1)
            }
        }
    }
    return result
}

同时识别您的多个下载的一种方法是跟踪从 DownloadManager 返回到您调用 objDownloadManager.enqueue(request) 时映射到给定条目的本地数据库的 ID。

DownloadManager.enquque 的文档表明:

Enqueue a new download. The download will start automatically once the download manager is ready to execute it and connectivity is available.

因此,如果您存储映射到给定记录的本地数据库条目的 ID,那么在 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)
                    // Find same id from db that you stored previously
                    val downloadManager =
                        getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
                    val uri: Uri = downloadManager.getUriForDownloadedFile(downloadedFileId)
                    viewModel.updateFirmwareFilePathToFirmwareTable(uri)
                }
            }
        }

在这里,it.getLong(DownloadManager.EXTRA_DOWNLOAD_ID) returns 您与之前开始下载并返回入队的相同 ID。

EXTRA_DOWNLOAD_ID 的文档表明:

Intent extra included with ACTION_DOWNLOAD_COMPLETE intents, indicating the ID (as a long) of the download that just completed.