4

I've been working on an app that needs to turn the flashlight on and off on an Android phone. I need a way to turn on the flashlight across ALL versions of Android above API 15. The problem is, on older phones (API < 21), I have to use the traditional way (below). But on newer phones, like my Nexus 6P, I have to use the Camera2 interface (below the below). Is there one way to have the flashlight torch work on ALL versions of Android with one set of code?

Below:

camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();

camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
// camera.release();  used later when app closes

Below the Below:

CameraManager cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, state);  // state is either true or false
Benjamin Owen
  • 608
  • 2
  • 10
  • 28
  • I see that the calls are deprecated, but not unusable. Could you not use the traditional way for all devices? – Bill Jul 13 '16 at 00:37
  • For some reason, no. My Nexus 6P doesn't work when using the normal API. The Android Monitor outputs: `E/Camera: Error 2`. I have looked up this error before with no help. Is there a list of camera errors somewhere or does the original API just not work? – Benjamin Owen Jul 13 '16 at 00:54
  • perhaps the answer here will help: http://stackoverflow.com/questions/34557157/android-flashlight-code-not-working?rq=1 – Bill Jul 13 '16 at 13:18

1 Answers1

2

A possible solution is to segment different sdk versions during runtime to determine which method to choose:

    private final int sdkVersion = Build.VERSION.SDK_INT;

    if (sdkVersion < Build.VERSION_CODES.LOLLIPOP) {
        //do old way
    } else {
        //do new way
    }

More information here: How to support multiple android version in your code?

Community
  • 1
  • 1
Bill
  • 4,506
  • 2
  • 18
  • 29