【问题标题】:Issue in getting file path获取文件路径的问题
【发布时间】:2021-07-15 07:46:58
【问题描述】:

我在 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")
}

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

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

【问题讨论】:

  • 文件尚未下载。您使用该代码还为时过早。
  • 我想是的,我该如何解决这个问题?
  • 为 ACTION_DOWNLOAD_COMPLETE 注册一个广播接收器。 (或者无论如何它被称为)。然后,您将从下载管理器中获得下载文件的 uri。所有非常标准的东西。你会发现到处都是代码。

标签: android kotlin android-download-manager


【解决方案1】:

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

首先在manifest.xml 文件中添加provider。喜欢

       <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>

file_paths.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) })

【讨论】:

    【解决方案2】:

    尝试注册BroadcastReceiver了解下载完成与否。喜欢:

        var onComplete: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(ctxt: Context, intent: Intent) {
            Log.d("TAG==>>","Download completed")
            val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), subFilePath)
            if (file.exists()) {
                Log.d("TAG==>>", "path >>>>>>>>>" + file.absolutePath)
            }else{
                Log.d("TAG==>>", "path >>>>>>>>> File not exists")
            }
        }
    }
    

    onCreate()里面注册broadCastReceiver就像registerReceiver(onComplete, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))

    onDestroy()里面注销broadCastReceiver点赞

     override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(onComplete)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多