1

我想在 Surfaceview 中显示我的前置摄像头之前显示一个权限对话框。但问题是,当我在显示权限对话框后单击允许按钮时,相机没有打开,并且表面视图只显示黑色,除非我重新启动我的活动,否则它会正常显示。实际上我看到已经发布了相同的问题,但我还没有找到答案。谢谢你的帮助。

这就是我打开前置摄像头的方式

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
    }

这就是我处理权限的方式

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()
            }
        }
    }
}
4

0 回答 0