在 Android 10+ 中,改进了对外部存储访问权限的限制,并引入了 Scoped Storage。它需要使用新的 API 来读取和写入外部存储的文件。如果要从图库中选择图片并跨配置文件进行访问,则可以按照以下步骤进行操作。
private val REQUEST_PERMISSIONS = 1001
private val PICK_IMAGE_REQUEST = 1002
private var selectedImageUri: Uri? = null
fun pickImage() {
val perm: Array = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
if (ContextCompat.checkSelfPermission(
applicationContext,
Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, perm, REQUEST_PERMISSIONS)
return
}
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, PICK_IMAGE_REQUEST)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSIONS -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
pickImage()
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
selectedImageUri = intent?.data
// 处理选择的图像
}
}
selectedImageUri?.let { uri ->
val projection = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(uri, projection, null, null, null)
if (cursor != null) {
cursor.moveToFirst()
val path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA