Android 通过 Intent Uri 检索图像失败:“无法访问内容..." [英] Android Retrieve Image by Intent Uri Failed: "has no access to content..."

查看:45
本文介绍了Android 通过 Intent Uri 检索图像失败:“无法访问内容..."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Intent to pick a photo from gallery:

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

    intent.type = "image/*"

    startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO)
}

并使用SharedPreferences保存图像uri:

And save the image uri using SharedPreferences:

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设置)时:

Saving has no problem, but when I retrieve it and convert to Bitmap (to set it with ImageView):

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

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

    imageView.setImageBitmap(bitmap)
}

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

I got this error: has no access to content://media/external/images/media/690726. Any help will be appreciated.

推荐答案

好吧,搜索实验了很多,解决方案如下:

Ok, searched and experimented a lot, here is the solution:

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

Just use Intent.ACTION_OPEN_DOCUMENT, that's enough. No need takePersistableUriPermission().

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

One more interesting finding: takePersistableUriPermission() doesn't work for Intent.ACTION_PICK and Intent.ACTION_GET_CONTENT. Which is too bad, because ACTION_PICK lanuches the gallery app, provides a better ui look, while ACTION_OPEN_DOCUMENT and ACTION_GET_CONTENT launches the native file explorer app.

这篇关于Android 通过 Intent Uri 检索图像失败:“无法访问内容..."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆