How to ask runtime camera permission after denied in android kotlin

Satheesh Guduri
2 min readDec 17, 2021
Android camera permission

Hello Everyone, In this article we will see about camera permission. While scanning qr code for that we are asking camera permission. User will able to see one dialog where he can allow or deny.

If he denies the permission, then how can we ask the user again. Let’s see

First step is we need to check whether user has enabled the camera permission or not

if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this@MainActivity,arrayOf(
Manifest.permission.CAMERA),
ABConstants.PERMISSION_REQUEST_CODE_CAMERA)
}

If permission is not enabled, then we will ask user by calling requestPermission function. Here user can select the option.

There are two options enable or disable. How can we know whether he enabled or not.

For that we have call back function like below.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {

ABConstants.PERMISSION_REQUEST_CODE_CAMERA ->
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
scanQROnceGranted()
} else {
showCameraDeniedAlertToUser()
}
}

If he granted the permission then we can call scanQROnceGranted() to scan the qr code.

If he not granted then we will show the user defined prompt/alert message like below.

private fun showCameraDeniedAlertToUser() {
AlertDialog.Builder(this, R.style.MyDialogTheme).apply {
setMessage(R.string.camera_aleret_message)
.setCancelable(false)
.setPositiveButton(R.string.action_settings) { _, _ ->
val cameraIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
val uri = Uri.fromParts("package", packageName, null)
data = uri
}

startActivity(cameraIntent)
}
setNegativeButton(R.string.cancel) { dialog, _ -> dialog.cancel() }
val alert = this.create()
alert.show()
}

}

Here, user will see a dialog with setting and cancel button and when user clicking on settings, then we will take him to the settings page by using above code. Once he granted, we check again granted or not and we go further.

That’s it. Thanks for reading this article. If you like my article please clap for me.

--

--