Turning on/off flash with Android camera2 API not working

Create these variables:

    public static final String CAMERA_FRONT = "1";
    public static final String CAMERA_BACK = "0";

    private String cameraId = CAMERA_BACK;
    private boolean isFlashSupported;
    private boolean isTorchOn;

then add these methods:

public void switchFlash() {
    try {
        if (cameraId.equals(CAMERA_BACK)) {
            if (isFlashSupported) {
                if (isTorchOn) {
                    mPreviewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                    mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, null);
                    flashButton.setImageResource(R.drawable.ic_flash_off);
                    isTorchOn = false;
                } else {
                    mPreviewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
                    mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, null);
                    flashButton.setImageResource(R.drawable.ic_flash_on);
                    isTorchOn = true;
                }
            }
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

public void setupFlashButton() {
    if (cameraId.equals(CAMERA_BACK) && isFlashSupported) {
        flashButton.setVisibility(View.VISIBLE);

        if (isTorchOn) {
            flashButton.setImageResource(R.drawable.ic_flash_off);
        } else {
            flashButton.setImageResource(R.drawable.ic_flash_on);
        }

    } else {
        flashButton.setVisibility(View.GONE);
    }
}

after this line add this code:

Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
isFlashSupported = available == null ? false : available;

setupFlashButton();

at the end call switchFlash() in your desired click listener.

et voilà!

PS. This might be helpful - front/back camera switcher


I see for cameraX, ImageCapture.flashMode only has effect during we build with initial configuration, ImageCapture.Builder() etc. But if you want to enable/disable flash dynamically, you will have to use the following.

camera?.cameraControl?.enableTorch(enableFlash)

If you are wondering what camera is? Captured it from documentation.

// A variable number of use-cases can be passed here -
// camera provides access to CameraControl & CameraInfo
camera = cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture
)