androidandroid-cameraxflashlight

How to Implement FlashToggle button in the camera app using cameraX?


How to Implement FlashToggle button in the camera app using cameraX? The flashlight should work properly along with the camera?

 @RequiresApi(Build.VERSION_CODES.M)
private fun toggleFlash()
{
    if(flash_toggle.isChecked)
    {
        try {
            cameraManager.setTorchMode(getCameraID, true)
        }
        catch(e: CameraAccessException){
            e.printStackTrace()
        }
    }
    else{
        try {
    cameraManager.setTorchMode(getCameraID,false)
        }
        catch(e: CameraAccessException){
            e.printStackTrace()
        }
    }
}

I Have used this but it only works when camera is off?


Solution

  • If you want to use a flash when capturing an image you can use:

    imageCapture.flashMode = ImageCapture.FLASH_MODE_ON for flash on

    imageCapture.flashMode = ImageCapture.FLASH_MODE_OFF for flash off

    imageCapture.flashMode = ImageCapture.FLASH_MODE_AUTO for flash auto

    If you want to use the torch(flashlight), you can use:

    // Enable torch
    camera.cameraControl.enableTorch(true)
    
    // Disable torch
    camera.cameraControl.enableTorch(false)
    

    Enable torch only after binding use cases.

    To obtain the Camera instance use:

    camera = cameraProvider.bindToLifecycle(...)