Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get torch (flash) state to toggle it in android M

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?

like image 362
lotdrops Avatar asked Mar 15 '23 15:03

lotdrops


1 Answers

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...

like image 139
yeberiah Avatar answered Mar 31 '23 21:03

yeberiah