在Android 11中,需要请求相机权限并使用MediaStore API来捕获照片。
示例代码:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED){ ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE) }
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val photoUri = getContentUri() intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri) startActivityForResult(intent, CAMERA_REQUEST_CODE)
private fun getContentUri(): Uri{
val contentValues = ContentValues()
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "filename")
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)!!
}
详细参考官方文档:https://developer.android.google.cn/training/camera/photobasics#Kotlin