Search code examples
javaandroidcameraflashlightandroid-hardware

Android JAVA QUESTION How do I turn on both the Camera and the Phone Flashlight?


currently I am making an app that requires both the phone camera and the phone flashlight to be turned on.

However I am having this problem where 1 overwrites the other. Probably since they are both using the same camera reference.

Please, does anyone know what I should do? Here is my function:

private void startCamera() {
        CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
        try {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {

                String pickedCamera = getCamera(manager);
                manager.setTorchMode(pickedCamera, true);
                manager.openCamera(pickedCamera, _cameraStateCallback, null);
                
                final int previewHeight = _previewSize.getHeight();
                final int previewWidth = _previewSize.getWidth();
                _imagePreviewReader = ImageReader.newInstance(previewWidth, previewHeight,
                        PixelFormat.RGBA_8888, MAX_IMAGES);

                _conversionScript = new YuvToRgb(_renderScript, _previewSize, CONVERSION_FRAME_RATE);
                _conversionScript.setOutputSurface(_imagePreviewReader.getSurface());
                _previewSurface = _conversionScript.getInputSurface();
            }

        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

Right now I have got another function that gets the camera "getCamera(manager)" and all that code seems to work totally fine, because when I run the app, the flashlight is turned on for a split second. After that the camera is being displayed. See manager.setTorchMode and manager.openCamera.

I am using the camera2 API.

Is there a way do have both the camera displayed and the flashlight turned on simultaneously?

............................


Solution

  • Yes, you can turn the flash on with the full camera2 API via the CaptureRequest fields CONTROL_AE_MODE and FLASH_MODE.

    Set CONTROL_AE_MODE to CONTROL_AE_MODE_ON to disable automatic flash firing, and also set FLASH_MODE to FLASH_MODE_TORCH to manually turn on the flash.

    To turn it off later, change FLASH_MODE to FLASH_MODE_OFF