首页 > 解决方案 > 获取文件路径的问题

问题描述

我在 kotlin - android 中使用下载管理器。成功下载文件如下:

fun downloadFirmwareFile(baseActivity: Context, url: String?, title: String?): Long {
    val direct = File(Environment.getExternalStorageDirectory().toString() + "/firmware")

    if (!direct.exists()) {
        direct.mkdirs()
    }
    val extension = url?.substring(url.lastIndexOf("."))
    val downloadReference: Long
    var dm: DownloadManager = baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    val uri = Uri.parse(url)
    val request = DownloadManager.Request(uri)

    var subPath = "bin" + System.currentTimeMillis() + extension
    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOCUMENTS,
            subPath)

    Log.e("File path >> ", Environment.DIRECTORY_DOCUMENTS + subPath)

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    request.setTitle(title)
    Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()

    downloadReference = dm?.enqueue(request) ?: 0


    downloadFirmwareLiveData.postValue("")

    var file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), subPath)
    if (file.exists()) {
        Log.e("path >>>>>>>>>", "path >>>>>>>>>" + file.absolutePath)
    }else{
        Log.e("path >>>>>>>>>", "path >>>>>>>>> File not exists")
    }
    return downloadReference
}

在这里,您可以看到我正在尝试获取下载的文件路径,如下所示:

var file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), subPath)
if (file.exists()) {
    Log.e("path >>>>>>>>>", "path >>>>>>>>>" + file.absolutePath)
}else{
    Log.e("path >>>>>>>>>", "path >>>>>>>>> File not exists")
}

但它给了我:路径>>>>>>>>> 文件不存在

可能是什么问题?请指导。

标签: androidkotlinandroid-download-manager

解决方案


如果您想创建自己的URI并将其用于下载内容,那么您可以使用以下代码。

首先添加文件providermanifest.xml喜欢

       <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

文件路径.xml

<paths>
<external-path name="external_files" path="."/>

您现在可以创建自己的URI并将download manager文件内容保存在其中。看下面的代码:

        fun downloadFirmwareFile(baseActivity: Context, url: String?, title: String?,saveFileUri: Uri): Long {
        
        val downloadReference: Long
        val dm: DownloadManager
        dm = baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val uri = Uri.parse(url)
        val request = DownloadManager.Request(uri)

        // Here uri is passed and image will be downloaded inside this file--
        request.setDestinationUri(saveFileUri)
/*    request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOCUMENTS,
            "bin" + System.currentTimeMillis() + extension)*/
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setTitle(title)
        Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()

        downloadReference = dm.enqueue(request) ?: 0

        return downloadReference
    }

你必须URI在开始下载之前创建。如下所示:

        downlodNowBtn.setOnClickListener {
        context?.let {
            createImageFile().let { downloadFile ->
                try {
                    // storing URI in a variable, so that it could be used further if required......
                    downloadedFileUri = Uri.fromFile(downloadFile)
                    Log.d("tisha==>>","File Uri= ${}")
                    // replace with your desired url----------------------------
                    downloadFirmwareFile(it,"https://homepages.cae.wisc.edu/~ece533/images/airplane.png","My photo", Uri.fromFile(downloadFile))
                }catch (e: java.lang.Exception){
                    Log.d("tisha==>>"," ${e.localizedMessage}")
                }
            }
        }
    }

    @Throws(IOException::class)
private fun createImageFile(): File {
    // Create an image file name
   // val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
    val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    return File(storageDir,"test.jpg")
}

现在您可以从以前存储的URI. 喜欢:

  val bitmap = BitmapFactory.decodeStream(downloadedFileUri?.let { it1 -> context?.contentResolver?.openInputStream(it1) })

推荐阅读