4

I have a torch / flashlight app using this code

Turn On

    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(params);
    camera.startPreview();

Turn Off

    params = camera.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(params);
    camera.stopPreview();

However now

android.hardware.Camera has been deprecated and It is advised to use the new camera2 api instead.

Any help on how I would use camera2 to turn on/off the device's flashlight?

Thank you for your help

KISHORE_ZE
  • 1,466
  • 3
  • 16
  • 26

2 Answers2

3

First, the deprecated android.hardware.Camera API still works fine, and if you need to support Android releases older than 5.0 Lollipop, you'll still need to use it.

The easiest option for the newest Android releases (Android Marshmallow or newer) is the new direct flashlight control: CameraManager.setTorchMode

It's very simple to use, and does not require the camera permission.

So I would recommend the following:

Pre-API 23, use the deprecated Camera API and your existing approach (don't forget to set a preview display as well, a dummy SurfaceTexture is simplest). You'll need the camera permission and runtime permission request handling.

API 23 or newer, use the setTorchMode call, and you don't even need to ask for any particular runtime permissions.

Eddy Talvala
  • 17,243
  • 2
  • 42
  • 47
0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String camID : mCameraManager.getCameraIdList()) {
                CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(camID);
                int lensFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
                if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT
                        && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
                    mCameraId = camID;
                    break;
                } else if (lensFacing == CameraCharacteristics.LENS_FACING_BACK
                        && cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
                    mCameraId = camID;
                }
                if (mCameraId != null) {
                    mCameraManager.setTorchMode(mCameraId, true);
                }
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
LokiDroid
  • 972
  • 10
  • 22