【问题标题】:Android 10 / API 29 Kotlin - download video to sub directory in picturesAndroid 10 / API 29 Kotlin - 将视频下载到图片中的子目录
【发布时间】:2021-06-09 19:19:30
【问题描述】:

我正在使用此代码下载视频:

val path = "Pictures/Appname"
val fileName = "example.mp4"
    
val request = DownloadManager.Request(Uri.parse(fileURL))
        .setDestinationInExternalPublicDir(path, fileName)

但它只适用于 API

从 API 29 开始,我只能通过以下方式将其下载到 Pictures 目录中:

.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, fileName)

即使子文件夹 Appname 存在于其中。

这里有什么问题?

我也尝试了其他问题的答案,但没有一个有效:

.setDestinationInExternalPublicDir(path, fileName)
.setDestinationInExternalFilesDir(this@DownloadFile, path, fileName)
.setDestinationUri(Uri.fromFile(File(path, fileName)))

我也接受没有 DownloadManager 的解决方案,只要它将视频下载到 Pictures/Appname,就像我在 API >= 29 中看到的其他应用程序一样

【问题讨论】:

  • 您没有告诉文件名的值。请把它也硬编码在你的帖子中。
  • 将该子目录放入文件名“appName/fileName”。
  • Yessss 这有效,但以斜线开头:“/appName/fileName”谢谢!请回答这个问题,我会接受
  • 你删除了你的答案??
  • 不,版主让-弗朗索瓦·法布尔(Jean-François Fabre)之前从未见过他。有些人不喜欢提到 cmets。我转发了。

标签: android kotlin android-download-manager


【解决方案1】:

下载管理器不需要存储到外部存储的权限。

创建子目录的答案在 cmets 中。

【讨论】:

    【解决方案2】:

    您是否请求访问要下载到的目录。由于 Android 10 及更高版本默认使用范围存储 (https://developer.android.com/about/versions/10/privacy/changes)。背后的想法是应用程序只能将数据存储到/Android/data/com.app.package.name/...,或者需要明确询问用户。然后,用户选择允许应用访问的文件夹 (https://developer.android.com/training/data-storage#scoped-storage)。这意味着会有一个面向用户的目录选择器。

    要求用户选择存储文件的文件夹的示例:

    val action = Intent.ACTION_CREATE_DOCUMENT
    val intent = Intent(action)
            .addCategory(Intent.CATEGORY_OPENABLE)
            .setType("mime/type") // Change this
            .also { it.putExtra(Intent.EXTRA_TITLE, filename) } // Optional: proposed file name
    startActivityForResult(intent, YOUR_REQUEST_CODE)
    

    用户选择文件夹后:

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) when (requestCode) {
            YOUR_REQUEST_CODE -> {
                val uri = data?.data
                // here you have the permission to write
                // into the file represented by the uri
            }
        }
    }
    

    【讨论】:

    • 此信息与 DownloadManager 无关。 DownloadMaager 不需要这些权限。它可以没有。
    • 更糟糕的是:对于 Intent.ACTION_CREATE_DOCUMENT,您不需要任何权限。
    【解决方案3】:

    这是解决方案:

    .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, "/appName/" + fileName)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-10
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      相关资源
      最近更新 更多