I want to show a permission dialog before showing my front camera in surfaceview. but the problem is when I click on allow button after the permission dialog showed, the camera is not opened and the surfaceview shows only black unless I restart my activity it show as normal. Actually I saw the same question has been posted but I could not find an answer yet. Thanks for any help.
This is how I open the front camera
private fun initializeCamera() {
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
private var mCamera: Camera? = null
override fun surfaceDestroyed(holder: SurfaceHolder) {
mCamera?.stopPreview()
mCamera?.release()
mCamera = null
}
override fun surfaceCreated(holder: SurfaceHolder) {
mCamera = getCameraInstance()
try {
mCamera?.setPreviewDisplay(holder)
} catch (exception: IOException) {
mCamera?.release()
mCamera = null
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int,
height: Int) {
mCamera?.startPreview()
}
})
}
fun getCameraInstance(): Camera? {
var c: Camera? = null
try {
c = openFrontFacingCamera()
} catch (e: Exception) {
Log.i("Error", "Cannot open camera.")
}
return c
}
private fun openFrontFacingCamera(): Camera? {
var cameraCount = 0
var cam: Camera? = null
val cameraInfo = Camera.CameraInfo()
cameraCount = Camera.getNumberOfCameras()
for (camIdx in 0 until cameraCount) {
Camera.getCameraInfo(camIdx, cameraInfo)
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx)
} catch (e: RuntimeException) {
Log.e("Error", "Camera failed to open: " + e.localizedMessage)
}
}
}
cam?.setDisplayOrientation(90)
return cam
}
This is how I handled the permission
if (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), 1)
return
}
initializeCamera()
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
1 -> {
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {}
GeneralHelper.runMainThread {
initializeCamera()
}
}
}
}