I've been working on an app that needs to turn the flashlight on and off on an Android phone. I need a way to turn on the flashlight across ALL versions of Android above API 15. The problem is, on older phones (API < 21), I have to use the traditional way (below). But on newer phones, like my Nexus 6P, I have to use the Camera2 interface (below the below). Is there one way to have the flashlight torch work on ALL versions of Android with one set of code?
Below:
camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
// camera.release(); used later when app closes
Below the Below:
CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, state); // state is either true or false