我正在尝试在我的Android上使用摄像头。用户将被提示输入摄像头的权限。之前我为它们使用了startActivityForResult和onRequestPermissionRequest。最近我发现它们被弃用了,所以我尝试使用registerForActivity。我设法更改为startActivity,但我被权限请求卡住了。我想知道我是否必须创建另一个permissionlauncher,或者我可以在我的resultlauncher中创建权限。
companion object{
private const val CAMERA_PERMISSION_CODE = 1
private const val CAMERA_REQUEST_CODE = 2
}
val checkpermission = Manifest.permission.CAMERA
var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
val DP: Bitmap = data!!.extras!!.get("data") as Bitmap
val image = findViewById<ImageView>(R.id.imageButtonVerifyPhoto)
image.setImageBitmap(DP)
}
}
val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
isGranted ->
if(isGranted){
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
resultLauncher.launch((intent))
Toast.makeText(this,"Permission is tested", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this,"Permission is denied",Toast.LENGTH_SHORT).show()
}
}
var cameraButton = findViewById<Button>(R.id.buttonRetakePhoto) // can change later
cameraButton.setOnClickListener {
if(ContextCompat.checkSelfPermission(
this,
checkpermission
) == PackageManager.PERMISSION_GRANTED
){
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
resultLauncher.launch(intent)
}else{
permissionLauncher.launch(checkpermission)
}
}
}
下面是我以前的onRequestPermission代码
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == CAMERA_REQUEST_CODE){
if(grantResults.isNotEmpty()&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, CAMERA_REQUEST_CODE)
}else{
Toast.makeText(this,"Permission is denied",Toast.LENGTH_SHORT).show()
}
}
}
3条答案
按热度按时间vpfxa7rd1#
请求运行时权限只是稍微简化了一点
现在,我们可以调用此函数来获取所需的任何类型的权限
确保添加
build.gradle
如果你想了解这一切是如何工作的检查这里
gojuced72#
2022年最新解决方案:(没有更多的请求代码)
1.创建帮助器扩展函数(用于
Fragment
):1.在
Fragment
中请求权限:9rygscc13#
您可以尝试Aaper,它允许使用如下注解请求权限:
首先,将权限添加到清单中:
然后,注解一个需要使用摄像头的方法:
就是这样,当你调用
takePhoto
方法时,它会检查摄像头权限,如果不可用,它会启动一个权限请求对话框,如果用户同意,它会继续运行takePhoto
的body。免责声明我是阿普的创造者