For 2021, with CameraX, it is now dead easy: https://stackoverflow.com/a/66585201/294884
For this problem you should:
Check whether the flashlight is available or not?
If so then Turn Off/On
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
In API 23 or Higher (Android M, 6.0)
Turn On code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null;
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Turn OFF code
camManager.setTorchMode(cameraId, false);
And Permissions
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
ADDITIONAL EDIT
People still upvoting my answer so I decided to post additional code This was my solution for the problem back in the day:
public class FlashlightProvider {
private static final String TAG = FlashlightProvider.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;
public FlashlightProvider(Context context) {
this.context = context;
}
private void turnFlashlightOn() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String cameraId = null;
if (camManager != null) {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
Log.e(TAG, e.toString());
}
} else {
mCamera = Camera.open();
parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
private void turnFlashlightOff() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
String cameraId;
camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
if (camManager != null) {
cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
} else {
mCamera = Camera.open();
parameters = mCamera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(parameters);
mCamera.stopPreview();
}
}
}
From my experience, if your application is designed to work in both portrait and landscape orientation, you need to declare the variable cam
as static. Otherwise, onDestroy()
, which is called on switching orientation, destroys it but doesn't release Camera so it's not possible to reopen it again.
package com.example.flashlight;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Camera cam = null;// has to be static, otherwise onDestroy() destroys it
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void flashLightOn(View view) {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOn()",
Toast.LENGTH_SHORT).show();
}
}
public void flashLightOff(View view) {
try {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH)) {
cam.stopPreview();
cam.release();
cam = null;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception flashLightOff",
Toast.LENGTH_SHORT).show();
}
}
}
to manifest I had to put this line
<uses-permission android:name="android.permission.CAMERA" />
from http://developer.android.com/reference/android/hardware/Camera.html
suggested lines above wasn't working for me.
I Got AutoFlash light with below simple Three Steps.
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.FLASHLIGHT"/> <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
In your Camera Code do this way.
//Open Camera
Camera mCamera = Camera.open();
//Get Camera Params for customisation
Camera.Parameters parameters = mCamera.getParameters();
//Check Whether device supports AutoFlash, If you YES then set AutoFlash
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
{
parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.
Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.
It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!
To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.
Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With