Android 安卓通过意向Uri检索图像失败:";无法访问内容……”;

Android 安卓通过意向Uri检索图像失败:";无法访问内容……”;,android,android-intent,android-image,android-file,android-storage,Android,Android Intent,Android Image,Android File,Android Storage,我使用Intent从图库中挑选照片: binding.pickPhotoButton.setOnClickListener { val intent = Intent(Intent.ACTION_PICK) intent.type = "image/*" startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO) } 并使用SharedReferences保存图像uri: object Data

我使用Intent从图库中挑选照片:

binding.pickPhotoButton.setOnClickListener {
    val intent = Intent(Intent.ACTION_PICK)

    intent.type = "image/*"

    startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO)
}
并使用
SharedReferences
保存图像uri:

object DataStore {
    fun saveImage(context: Context, imageName: String, imageUri: Uri) {
        val sharedPreferences = context.getSharedPreferences("images", Context.MODE_PRIVATE)

        sharedPreferences.edit {
            putString(imageName, imageUri.toString())
        }
    }

    fun getImageUri(context: Context, imageName: String): Uri? {
        val sharedPreferences = context.getSharedPreferences("images", Context.MODE_PRIVATE)
        val uriString = sharedPreferences.getString(imageName, "")

        return if (uriString!!.isEmpty()) null else uriString.toUri()
    }
}
保存没有问题,但是当我检索它并将其转换为
位图时(要使用
图像视图设置它
):


我遇到此错误:
无法访问content://media/external/images/media/690726
。任何帮助都将不胜感激。

重新启动应用程序后,或者如果您在其他活动中使用uri,则uri的读取权限已消失

但有一个解决办法


在onActivityResult()中使用ACTION\u OPEN\u DOCUMENT并对获取的uri获取持久化uri权限,而不是ACTION\u PICK使用ACTION\u OPEN\u DOCUMENT。

好的,进行了大量搜索和实验,以下是解决方案:

只要使用
Intent.ACTION\u OPEN\u DOCUMENT
,就足够了。无需
takePersistableUriPermission()



还有一个有趣的发现:
takePersistableUriPermission()
不适用于
Intent.ACTION\u PICK
Intent.ACTION\u GET\u CONTENT
。这太糟糕了,因为
ACTION\u PICK
lanuches画廊应用程序,提供了更好的界面外观,而
ACTION\u OPEN\u DOCUMENT
ACTION\u GET\u CONTENT
启动本机文件资源管理器应用程序。

您在activityresult中解码输入流。看起来不错。哪里有
val bitmap=BitmapFactory.decodeStream(it)
。URI在组件活动或您访问的片段的生存期内有效
URI在组件活动或您访问的片段的生存期内有效
听起来很重要,我在重新启动应用程序时遇到了这个错误。这意味着我必须在某处创建一个图像文件的副本,然后我可以检索它,对吗?。我想你需要通过再次选取图像或创建本地副本来获取uri。非常感谢<代码>操作\u打开\u文档
完成了工作。无需
获取PersistableUriPermission()
val inputStream = imageView.context.contentResolver.openInputStream(uri)

inputStream.use {
    val bitmap = BitmapFactory.decodeStream(it)

    imageView.setImageBitmap(bitmap)
}