Turn on and turn off flash light programmatically in Android

Most of times we need to use flash light of our Android device as torch so we have to start camera or other application. But Android provide access to the camera flash in our application so you can turn it on and off using code. Here I’ll show you how to turn on and off it programmatically.

First of all we need to check if the device has the flash light or not. For that we use following condition from PackageManager.

Here is the function for turn on the flash light.

Camera cam = null;
public void turnOnFlashLight() {
    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 throws in turning on flashlight.", Toast.LENGTH_SHORT).show();
    }
}

And to turn of flashlight use following piece of code.

public void turnOffFlashLight() {
    try {
        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
            cam.stopPreview();
            cam.release();
            cam = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Exception throws in turning off flashlight.", Toast.LENGTH_SHORT).show();
    }
}

Here we use Camera class for flashlight.

Here we need to add the following permission to the manifest file. The last one is not generally used in 3rd party apps, it is just use for testing in system apps as per docs.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.HARDWARE_TEST" />

Here you can download full code from github: Flashligh Demo

You can download demo app from Google Play: Flashlight Demo