Android - Camera2 : The easiest way to turn on the

2019-09-20 05:19发布

问题:

The simplest way to turn on the torch light was :

Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();

The simplest way to turn it off was :

Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();

But, as the Camera class is now deprecated, what is the easiest way to achieve the same result with the Camera2 class? I only found long and complicated solutions...

回答1:

check the answer from Daniel Netzer here you just need to write 3 line to turn on torch

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position and back camera is 1.
camManager.setTorchMode(cameraId, true);