Android 通过 Intent Uri 检索图像失败:“无法访问内容...”

问题描述

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

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

    intent.type = "image/*"

    startActivityForResult(intent,REQUEST_CODE_PICK_PHOTO)
}

并使用 SharedPreferences 保存图像 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()
    }
}

保存没有问题,但是当我检索它并转换为 Bitmap(用 ImageView 设置)时:

val inputStream = imageView.context.contentResolver.openInputStream(uri)

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

    imageView.setimageBitmap(bitmap)
}

我收到此错误has no access to content://media/external/images/media/690726。任何帮助将不胜感激。

解决方法

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

但是有一个解决方案。

使用 ACTION_OPEN_DOCUMENT 代替 ACTION_PICK 并为 onActivityResult() 中获取的 uri 获取持久化 uri 权限。

,

好吧,搜索和试验了很多,这里是解决方案:

Intent.ACTION_OPEN_DOCUMENT就够了。不需要takePersistableUriPermission()


另一个有趣的发现:takePersistableUriPermission() 不适用于 Intent.ACTION_PICK Intent.ACTION_GET_CONTENT。这太糟糕了,因为 ACTION_PICK 启动了图库应用程序,提供了更好的 ui 外观,而 ACTION_OPEN_DOCUMENTACTION_GET_CONTENT 启动了本机文件浏览器应用程序。