简体   繁体   English

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

[英]Identifying the particular file after downloaded using Download Manager in Android

I am calling below function to download a binary file.我正在调用下面的函数来下载一个二进制文件。

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
    }

Once the file got downloaded I am receiving it in below onReceive() method of Broadcast receiver:下载文件后,我将在下面的广播接收器的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)
                    }
                }
            }

I am downloading the files one by one and wants to know that which file is downloaded.我正在一一下载文件,想知道下载的是哪个文件。 Based on the particular file download, I have to update the entry in my local database.根据特定的文件下载,我必须更新本地数据库中的条目。

So, here in onReceive() method how can I identify that which specific file is downloaded?那么,在 onReceive() 方法中,如何识别下载了哪个特定文件?

Thanks.谢谢。

You have the Uri of file, now simply get the file name to identify the file, you can use following function to get file name你有文件的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
}

One way to identify your multiple downloads simultaneously is to track id returned from DownloadManager to your local db mapped to given entry when you call objDownloadManager.enqueue(request) .同时识别您的多个下载的一种方法是跟踪从DownloadManager返回到映射到给定条目的本地数据库的 id,当您调用objDownloadManager.enqueue(request)

Document of DownloadManager.enquque indicates that: DownloadManager.enquque文件表明:

Enqueue a new download.加入新的下载队列。 The download will start automatically once the download manager is ready to execute it and connectivity is available.一旦下载管理器准备好执行下载并且连接可用,下载将自动开始。

So, if you store that id mapped to your local database entry for given record then during onReceive() you can identify back to given record.因此,如果您存储映射到给定记录的本地数据库条目的 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)
                }
            }
        }

Here, it.getLong(DownloadManager.EXTRA_DOWNLOAD_ID) returns you the same id for which download was started previously and enqueue returned.在这里, it.getLong(DownloadManager.EXTRA_DOWNLOAD_ID)返回与之前下载启动并返回 enqueue 相同的 ID。

Document for EXTRA_DOWNLOAD_ID indicates that: EXTRA_DOWNLOAD_ID 的文档表明:

Intent extra included with ACTION_DOWNLOAD_COMPLETE intents, indicating the ID (as a long) of the download that just completed.包含在 ACTION_DOWNLOAD_COMPLETE 意图中的额外意图,指示刚刚完成的下载的 ID(长)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM