0
Camera cam = Camera.Open();
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();

that there is no support in the new Android Camera? And only need to use Camera2? It will run a new class Camera2 on older devices?

mtb
  • 101
  • 1

2 Answers2

1

Marshmallow has a new Flashlight API with setTorchMode().

Darrell
  • 1,945
  • 15
  • 21
  • I haven't tested it, but maybe setTorchMode does not require camera permission (openCamera definitely does). It would be nice if random flashlight apps didn't have the ability to take pictures! – Darrell Oct 25 '15 at 17:16
1

Your code does not set a preview target with either Camera.setPreviewDisplay or Camera.setPreviewTexture.
That's required by the API for preview to operate, though many devices unfortunately don't enforce this (which is a problem when you then run your app on a strict device).

If you don't want to draw a preview, then just create a dummy SurfaceTexture:

Camera cam = Camera.Open();
Camera.Parameters p = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
SurfaceTexture dummy = new SurfaceTexture(1);
cam.setPreviewTexture(dummy);
cam.startPreview();

And make sure that you don't let the dummy SurfaceTexture object get garbage-collected while the camera is running.

That said, the new torch API in Marshmallow is very simple to use and does not require the camera permission, so I recommend you use it whenever possible.

Eddy Talvala
  • 17,243
  • 2
  • 42
  • 47
  • I hope Flashlight API will work on old device such as android 2.3 & below... But I not found information about support old version android new Flashlight API – mtb Oct 25 '15 at 21:06
  • 1
    The Flashlight cannot work on older releases, since it is part of the core OS APIs. For anything before Android 6.0, you still have to open the camera device and turn on preview. – Eddy Talvala Oct 26 '15 at 09:21
  • You don't have to set preview if you just need to flash in torch mode – Louis CAD Jan 12 '16 at 07:04
  • Louis CAD - that's not true. The camera API documentation states that a preview target is always required. Some devices are more relaxed about this, which is confusing, but if you want to work on all Android devices, don't skip that step! – Eddy Talvala Jun 03 '16 at 00:53