How To Turn On/Off Camera LED / Flashlight In Android


           Your LED flash can be turned into a Flashlight using the Android camera parameter 'FLASH_MODE_TORCH'
This camera parameter initiates constant emission of light from the flash.
To access the device camera from the code we need to add below two permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

These are the steps followed in this example:
1. Check if the device supports camera
2. If the device supports camera, check if the camera supports flash
3. If the camera supports flash, add 'FLASH_MODE_TORCH' parameter and initiate camera preview.

I have added a toggle button to turn the camera on and off.
Tip:To know more about Android ToggleButton, go to this tutorial.

If the device does not have the camera[or] camera flash support, alert will be displayed to the user.
Tip: To know more about Android Alert dialogs, go to this tutorial.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.flashlight"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

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

    <uses-feature android:name="android.hardware.camera" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.flashlight.FlashlightActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Layout file:
flashlight.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <ToggleButton
        android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:onClick="onToggleClicked"
        android:textOff="Turn Flashlight on"
        android:textOn="Turn Flashlight off"/>

</RelativeLayout>

Activity class:
FlashlightActivity.java

package com.example.flashlight;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ToggleButton;

/**
 * @author Prabu 
 * July 30 2013
 * @version 1.0
 * 
 */
public class FlashlightActivity extends Activity {
 private Camera camera;
 private ToggleButton button;
 private final Context context = this;
 /**
  * @see android.app.Activity#onStop()
  */
 @Override
 protected void onStop() {
  super.onStop();
  if (camera != null) {
   camera.release();
  }
 }

 /**
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.flashlight);
  button = (ToggleButton) findViewById(R.id.togglebutton);
  
  final PackageManager pm = context.getPackageManager();
  if(!isCameraSupported(pm)){
   AlertDialog alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("No Camera");
      alertDialog.setMessage("The device's doesn't support camera.");
      alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
          public void onClick(final DialogInterface dialog, final int which) { 
           Log.e("err", "The device's doesn't support camera.");
          }
       });
   alertDialog.show();
  }
  camera = Camera.open();
 }
 public void onToggleClicked(View view) {
  PackageManager pm=context.getPackageManager();
  final Parameters p = camera.getParameters();
  if(isFlashSupported(pm)){
   boolean on = ((ToggleButton) view).isChecked();
   if (on) {
    Log.i("info", "torch is turn on!");
    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
    camera.setParameters(p);
    camera.startPreview();
   } else {
    Log.i("info", "torch is turn off!");
    p.setFlashMode(Parameters.FLASH_MODE_OFF);
    camera.setParameters(p);
    camera.stopPreview();
   }
  }else{
   button.setChecked(false);
   AlertDialog alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("No Camera Flash");
      alertDialog.setMessage("The device's camera doesn't support flash.");
      alertDialog.setButton(RESULT_OK, "OK", new DialogInterface.OnClickListener() {
          public void onClick(final DialogInterface dialog, final int which) { 
           Log.e("err", "The device's camera doesn't support flash.");
          }
       });
   alertDialog.show();
  }
 }
 /**
  * @param packageManager
  * @return true <b>if the device support camera flash</b><br/>
  * false <b>if the device doesn't support camera flash</b>
  */
 private boolean isFlashSupported(PackageManager packageManager){ 
  // if device support camera flash?
  if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
   return true;
  } 
  return false;
 }

 /**
  * @param packageManager
  * @return true <b>if the device support camera</b><br/>
  * false <b>if the device doesn't support camera</b>
  */
 private boolean isCameraSupported(PackageManager packageManager){
  // if device support camera?
  if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
   return true;
  } 
  return false;
 }
}


Output:
Flashlight off
Flashlight OFF

Flashlight on
Flashlight ON

No camera error



Source code of this example:
FlashLight.zip






Reactions:

4 comments :

  1. Thanks!!! you're great!

    ReplyDelete
  2. Hi,
    would you please tell me how to test if the camera is on or off.
    Thanks

    ReplyDelete
  3. when write any function with the Camera class object it gives error that the function is undefined for the type Camera.
    e.g,
    Camera camera;
    camera.stopPreview();
    it gives that error "The method stopPreview() is undefined for the type Camera"
    and also for all the methods used with the Camera object
    Please help me i cant figure it..

    Thanks

    ReplyDelete
  4. How to make the flash light work even when the user comes out of the app. Could you please tell me how it is done.

    Thanks in advance.
    Ashok prakash

    ReplyDelete