Use Camera Flashlight in Android

Use camera flashlight in Android

Every device is a bit different. Samsung especially likes to make things complicated for app developers.

On the Galaxy Tab you should be good with:

Camera cam;
void ledon() {
cam = Camera.open();
Parameters params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
cam.setParameters(params);
cam.startPreview();
cam.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
}

void ledoff() {
cam.stopPreview();
cam.release();
}

If that doesn't work then it might be a matter of setting FLASH_MODE_OFF initially and changing it after the startPreview.

How to turn on front flash light programmatically in Android?

For 2021, with CameraX, it is now dead easy: https://stackoverflow.com/a/66585201/294884


For this problem you should:

  1. Check whether the flashlight is
    available or not?

  2. If so then Turn Off/On

  3. If not then you can do whatever, according to your app
    needs.

For Checking availability of flash in the device:

You can use the following:

 context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

which will return true if a flash is available, false if not.

See:
http://developer.android.com/reference/android/content/pm/PackageManager.html for more information.

For turning on/off flashlight:

I googled out and got this about android.permission.FLASHLIGHT. Android manifests' permission looks promising:

 <!-- Allows access to the flashlight -->
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="@string/permlab_flashlight"
android:description="@string/permdesc_flashlight" />

Then make use of Camera and set Camera.Parameters. The main parameter used here is FLASH_MODE_TORCH.

eg.

Code Snippet to turn on camera flashlight.

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

Code snippet to turn off camera led light.

  cam.stopPreview();
cam.release();

I just found a project that uses this permission. Check quick-settings' src code. here http://code.google.com/p/quick-settings/ (Note: This link is now broken)

For Flashlight directly look http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/#quick-settings/src/com/bwx/bequick/flashlight (Note: This link is now broken)

Update6
You could also try to add a SurfaceView as described in this answer LED flashlight on Galaxy Nexus controllable by what API?
This seems to be a solution that works on many phones.

Update 5 Major Update

I have found an alternative Link (for the broken links above): http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com.bwx.bequick.flashlight.htm You can now use this link. [Update: 14/9/2012 This link is now broken]

Update 1

Another OpenSource Code :
http://code.google.com/p/torch/source/browse/

Update 2

Example showing how to enable the LED on a Motorola Droid: http://code.google.com/p/droidled/

Another Open Source Code :

http://code.google.com/p/covedesigndev/

http://code.google.com/p/search-light/

Update 3 (Widget for turning on/off camera led)

If you want to develop a widget that turns on/off your camera led, then you must refer my answer Widget for turning on/off camera flashlight in android.

Update 4

If you want to set the intensity of light emerging from camera LED you can refer Can I change the LED intensity of an Android device? full post. Note that only rooted HTC devices support this feature.

** Issues:**

There are also some problems while turning On/Off flashlight. eg. for the devices not having FLASH_MODE_TORCH or even if it has, then flashlight does not turn ON etc.

Typically Samsung creates a lot of problems.

You can refer to problems in the given below list:

Use camera flashlight in Android

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

What is the use of android.permission.FLASHLIGHT?

The <uses-permission android:name="android.permission.CAMERA" /> already has the option to use the flashlight.

But <uses-permission android:name="android.permission.FLASHLIGHT" /> only allows the user to use the flashlight without activating the camera hardware.

This means:

  • Use <uses-permission android:name="android.permission.CAMERA" /> if you want to develop an app that uses camera and flashlight.
  • Use <uses-permission android:name="android.permission.FLASHLIGHT" /> if you want to develop an app that ONLY uses flashlight.

But, some users have seen crashes using the <uses-permission android:name="android.permission.FLASHLIGHT" /> permission in their apps. So, you can use both of them to make sure your app is working without crashes (For example: Which permissions are required for Flashlight?)

How to automatically turn on flashlight for video recording when the scene is dark?

Finally figured this out, gpuser's answer used the right flag but it is not complete - still need to code the callback and turn on the torchlight when needed.

I also found that for video recording, we still use the same Camera2 API init and configuration steps, just that some of the callbacks will be fired multiple times, so I added a flag to perform the flash detection only once.

1)After camera started capturing, run this code

performAutoTorchDetectionOnce = true; // set this flag first, will be used later
captureRequestBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); // CONTROL_AE_MODE_ON_AUTO_FLASH is important here, to enable flash detection
captureSession.setRepeatingRequest(captureRequestBuilder.build(), captureCallback, null);

2)And this is my captureCallback implementation, change it depending on your needs. The gist of it is that eventually the camera capture will fall into one of the two states, CONTROL_AE_STATE_CONVERGED or CONTROL_AE_STATE_FLASH_REQUIRED. These two states mean that auto exposure algorithm has finished running, if it is converged means no flash is needed whereas flash_required will mean that we have to turn on flash. In the latter we will then need to manually turn on the flash in the next step.

private CameraCaptureSession.CaptureCallback captureCallback =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(CameraCaptureSession session, CaptureRequest request,
long timestamp, long frameNumber) {
super.onCaptureStarted(session, request, timestamp, frameNumber);
}

@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);

Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
if (aeState != null) {
if (performAutoTorchDetectionOnce) {
if (aeState == CameraMetadata.CONTROL_AE_STATE_CONVERGED // CONTROL_AE_STATE_CONVERGED means Auto-exposure has finished
|| aeState == CameraMetadata.CONTROL_AE_STATE_FLASH_REQUIRED) { // CONTROL_AE_STATE_FLASH_REQUIRED means Auto-exposure has finished, but flash is required
performAutoTorchDetectionOnce = false;
enableTorch(aeState == CameraMetadata.CONTROL_AE_STATE_FLASH_REQUIRED);
}
}
}
}
};

3)Here's the enableTorch implementation. I tried leaving CONTROL_AE_MODE as CONTROL_AE_MODE_ON_AUTO_FLASH but it didn't work, torch light does not turn on, so I have to change it to CONTROL_AE_MODE_ON.

public synchronized void enableTorch(boolean enable) {
Timber.d("enableTorch(" + enable + ") called");
try {
if (isCaptureStarted()) {
if (enable) {
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
} else {
captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
}
captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
captureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
}
} catch (CameraAccessException e) {
Timber.e(e, "enableTorch(" + enable + ") failed: ");
}
}

Android Turn on/off Camera Flash Programmatically with Camera2

I'll be addressing you to the Android Dev. documentation about the CameraManager since more code will be required but this is the basic code to activate the Flash on the camera in API's above 21.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, true);

Android CameraManager documentation.

Android.hardware.camera2 documentation.

very important thing to remember that you will need to use try/catch to discard possible errors and ofcourse check that no other higher priority application is using the camera at the moment.

How to keep the flashlight on (programmatically) while the camera preview is ON

Try this while previewing on SurfaceView

params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(params);

Remember that If you want to use it as flashlight you can do:

parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

If not, to turn flash on which will come out when you take the picture, you use:

parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);

Happy Coding!



Related Topics



Leave a reply



Submit