Example usage for android.hardware.camera2 CameraManager setTorchMode

List of usage examples for android.hardware.camera2 CameraManager setTorchMode

Introduction

In this page you can find the example usage for android.hardware.camera2 CameraManager setTorchMode.

Prototype

public void setTorchMode(@NonNull String cameraId, boolean enabled) throws CameraAccessException 

Source Link

Document

Set the flash unit's torch mode of the camera of the given ID without opening the camera device.

Usage

From source file:com.android.launcher3.Utilities.java

public static void turnOffFlashLight(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        CameraManager camManager = (CameraManager) context.getApplicationContext()
                .getSystemService(Context.CAMERA_SERVICE);
        String cameraId = null;//w ww .  j  a va2  s. c  o  m
        try {
            cameraId = camManager.getCameraIdList()[0];
            camManager.setTorchMode(cameraId, false);
            isFlashLightOn = false;
        } catch (CameraAccessException e) {
            isFlashLightOn = true;
            e.printStackTrace();
        }
    } else {
        try {
            if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
                cam.stopPreview();
                cam.release();
                cam = null;
                isFlashLightOn = false;
            }
        } catch (Exception e) {
            isFlashLightOn = true;
            e.printStackTrace();
        }
    }
}

From source file:com.android.launcher3.Utilities.java

public static void turnOnFlashLight(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        CameraManager camManager = (CameraManager) context.getApplicationContext()
                .getSystemService(Context.CAMERA_SERVICE);
        String cameraId = null;//  www . j  a  v  a  2s  .  c  om
        try {
            cameraId = camManager.getCameraIdList()[0];
            camManager.setTorchMode(cameraId, true);
            isFlashLightOn = true;
        } catch (CameraAccessException e) {
            isFlashLightOn = false;
            e.printStackTrace();
        }
    } else {
        try {
            if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
                Camera cam = Camera.open();
                Camera.Parameters p = cam.getParameters();
                p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                cam.setParameters(p);
                cam.startPreview();
                isFlashLightOn = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            isFlashLightOn = false;
        }
    }
}