Android 通过 Intent Uri 检索图像失败:"has no access to content..."

Android Retrieve Image by Intent Uri Failed: "has no access to content..."

我使用 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。任何帮助将不胜感激。

在您的应用重启后或者如果您在另一个 activity.

中使用该 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 启动本机文件浏览器应用程序。