【问题标题】:File Provider Exception : Failed to find configured root that contains文件提供程序异常:找不到配置的根目录,其中包含
【发布时间】:2020-03-10 12:18:18
【问题描述】:

我正在尝试使用相机 Intent 捕获图像并将其发送到服务器。

我已经关注了官方文档https://developer.android.com/training/camera/photobasics

但是在使用 FileProvider 从文件路径中获取 Uri 时出现异常。

我遇到了异常

未能找到包含 /storage/emulated/0/Android/data/com.example.app/files/Pictures/JPEG_20200310_160944_8900302509758571991.jpg 的已配置根目录

代码:

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <external-files-path name="my_images" path="Android/data/com.example.app/files" />
</paths>

AndroidManifest.xml

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.app.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
</provider>

CameraActivity.kt

private fun dispatchTakePictureIntent() {
    Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
        takePictureIntent.resolveActivity(packageManager)?.also {
            val photoFile: File? = try {
                viewModel.createFile()
            } catch (ex: IOException) {
                // Error occurred while creating the File
                null
            }
            photoFile?.also {
                 photoURI= FileProvider.getUriForFile(
                    this,
                    "com.example.app.fileprovider",
                    it
                )
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
            }
        }
    }
}

请帮我找出我错在哪里。

虽然我已经在 stackoverflow 上检查了可能的答案,但无法解决。

【问题讨论】:

标签: android kotlin androidx android-fileprovider


【解决方案1】:

替换:

path="Android/data/com.example.app/files"

与:

path="."

&lt;external-files-path&gt; 已经指向您在path 中标识的位置。

【讨论】:

  • 我得到的 URI 如下 content://com.example.app.fileprovider/my_images/Pictures/JPEG_20200310_185418_5229824733138978989.jpg 当我尝试访问该文件时给 /my_images/Pictures/JPEG_20200310_185418_5229824733138978989.jpg (没有这样的文件或目录) @CommonsWare
  • “我得到的 URI 如下 content://com.example.app.fileprovider/my_images/Pictures/JPEG_20200310_185418_5229824733138978989.jpg”——这似乎是正确的。 “当我尝试访问文件时,它给出了 /my_images/Pictures/JPEG_20200310_185418_5229824733138978989.jpg(没有这样的文件或目录)”——大概是你在 Uri 上调用 getPath() 并试图用它做点什么。别那样做。你已经有了File——你正在将它传递给getUriForFile()
  • 作为替代答案 - 我已成功使用 &lt;external-files-path name="my_images" path="Pictures" /&gt;val location = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多