I want to implement toggle torch functionality. So that the camera does not get captured and crash - as in Lollipop - I am attempting it with setTorchMode
in API 23.
I have a code implementation to turn on or off the torch; however, I don't know how to check the current state of the flash.
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String[] cameras = manager.getCameraIdList();
for (int i = 0; i < cameras.length; i++) {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameras[i]);
boolean flashAvailable = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
if (flashAvailable) {
boolean flashState = getFlashState(); //MISSING METHOD
manager.setTorchMode(cameras[i], !flashState);
}
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
So, how do I implement getFlashState
without using the old camera API? And is it possible to do it without capturing the camera?
You can try using
CameraManager.TorchCallback torchCallback = new TorchCallback() {
@Override
public void onTorchModeUnavailable(String cameraId) {
super.onTorchModeUnavailable(cameraId);
}
@Override
public void onTorchModeChanged(String cameraId, boolean enabled) {
super.onTorchModeChanged(cameraId, enabled);
flashState = enabled;
}
};
and register callback with
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
manager.registerTorchCallback(torchCallback, null);// (callback, handler)
when you want to turn on / off the flash uses
manager.setTorchMode(cameras[i], !flashState);
Remember unregister callback...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With