Turning on flashlight while using camera preview

730 Views Asked by At

I have the standard code of toggling flashlight:

    @RequiresApi(Build.VERSION_CODES.M)
    private fun flashlightOff() {
        val cameraManager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        cameraManager.setTorchMode(cameraId, false)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun flashlightOn() {
        val cameraManager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        val cameraId = cameraManager.cameraIdList[0]
        cameraManager.setTorchMode(cameraId, true)
    }

However, this logic fails if I use it with a camera preview (i.e <androidx.camera.view.PreviewView). Is there any way to override the flashlight while using the camera or a completely different logic than mentioned above?

The code I use to start the camera preview is below:

    private fun startCamera() {
    val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
    cameraProviderFuture.addListener(Runnable {
        // Used to bind the lifecycle of cameras to the lifecycle owner
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        // Preview
        val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(viewFinder.createSurfaceProvider())
                }

        imageCapture = ImageCapture.Builder().build()

        // Select back camera as a default
        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        try {
            // Unbind use cases before rebinding
            cameraProvider.unbindAll()

            // Bind use cases to camera
            camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
            camera!!.cameraControl.setLinearZoom(.50F)
        } catch (exc: Exception) {
            Log.e(TAG, "Use case binding failed", exc)
        }

    }, ContextCompat.getMainExecutor(this))
}
1

There are 1 best solutions below

0
Abhinav Prakash On

Found a solution where you could enable torch while using androidx.camera.view.PreviewView

@RequiresApi(Build.VERSION_CODES.M)
private fun flashlightOff() {
    camera.cameraControl.enableTorch(false)
}

@RequiresApi(Build.VERSION_CODES.M)
private fun flashlightOn() {
    camera.cameraControl.enableTorch(true)
}

Also make sure to add camera.cameraInfo.hasFlashUnit() after initializing camera