gpt4 book ai didi

android - 如何在kotlin中获得许可结果

转载 作者:行者123 更新时间:2023-12-05 09:28:18 25 4
gpt4 key购买 nike

我正在尝试在我的安卓设备上使用摄像头。用户将被提示获得相机的许可。以前我为他们使用了 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()
}
}
}

最佳答案

请求运行时权限只是简单了一点

private val requestPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
// do something
}

现在我们可以调用它来获得你想要的任何类型的权限

cameraButton.setOnClickListener {

if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
// Pass any permission you want while launching
requestPermission.launch(Manifest.permission.CAMERA)
}
}

确保在build.gradle中添加

implementation 'androidx.fragment:fragment-ktx:1.2.0' // or later
implementation 'androidx.activity:activity-ktx:1.3.0' // or later

如果您想了解这一切的工作原理,请查看 here

关于android - 如何在kotlin中获得许可结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71465812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com