0

I am trying to make a torchlight app but I am not able to turn it on properly. I have used the following logic to turn it on. Please let me know where I am going wrong. When I run this on my android phone it runs properly but the flashlight doesn't start.

if (count[0] == 0) {
    count[0] = 1;
    ((TransitionDrawable) imageView.getDrawable()).startTransition(3000);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String cameraId = null; // Usually back camera is at 0 position.
        try {
            cameraId = camManager.getCameraIdList()[0];
            camManager.setTorchMode(cameraId, true);   //Turn ON
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
} else {
    count[0] = 0;
    ((TransitionDrawable) imageView.getDrawable()).reverseTransition(3000);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        CameraManager camManager1 = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String cameraId = null; // Usually back camera is at 0 position.
        try {
            cameraId = camManager1.getCameraIdList()[0];
            camManager1.setTorchMode(cameraId, false);   //Turn ON
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
lmgguy
  • 89
  • 2
  • 8

1 Answers1

1

The code you have written is fully functional on Android Marshmallow+.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

This line checks for what version of Android you are running the app on. It executes the code within the if block only on Android version 6+ (API level 23+).

You need to add the else part with an older way of turning the flashlight on like this method: How to turn on camera flash light programmatically in Android?

Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55