How to change legacy camera class on Android
Previously, the flashlight function could be used using the Camera class. But now that all the Camera and Camera classes in the android.hardware packages are deprecated, I have to alternatively use some of the other classes in the android.hardware.camera2 package.
Traditionally I coded the flashlight part like this.
// getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
But now with the new API I am so confused about how to use the new one. Can someone please explain?
+3
user5040476
source
to share
1 answer
for flashlight I advise to use Camera2 API only with Android 6 (api 23), my flashlight toggle function looks like
@TargetApi(Build.VERSION_CODES.M)
public void toggleMarshmallowFlashlight(boolean enable) {
try {
final CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
final String[] list = manager.getCameraIdList();
manager.setTorchMode(list[0], enable);
} catch (CameraAccessException e) {
}
}
+1
source to share