255

I want to turn on front flash light (not with camera preview) programmatically in Android. I googled for it but the help i found referred me to this page

Does anyone have any links or sample code?

saiket
  • 3,063
  • 5
  • 18
  • 10
  • 2021 .. It's now dead easy in modern android .. https://stackoverflow.com/a/66585201/294884 – Fattie Mar 11 '21 at 15:10

12 Answers12

415

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

Fattie
  • 27,874
  • 70
  • 431
  • 719
Kartik Domadiya
  • 29,868
  • 19
  • 93
  • 104
  • 3
    Thanks for your help, It works for me! -- I just copied the interface Flashlight and the class HtcLedFlashlight then i just call setOn method with true/false HtcLedFlashlight and that it. --- Interface-Flashlight http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/src/com/bwx/bequick/flashlight/Flashlight.java -- Class-HtcLedFlashlight http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/src/com/bwx/bequick/flashlight/HtcLedFlashlight.java – saiket May 20 '11 at 10:31
  • 2
    @saiket : welcome.. if your problem is solved then mark this answer as solved. so that it can be useful to others.. – Kartik Domadiya May 20 '11 at 10:32
  • @Kartik i used u r code this, but i am facing problem here is after 2 sec light goes to off, if i press again on button it gives force close why. please tell me. – RajaReddy PolamReddy Nov 14 '11 at 07:03
  • 1
    @PolamReddyRajaReddy : I think you are testing in Samsung Device. Am i correct ? – Kartik Domadiya Nov 14 '11 at 07:09
  • @RajaReddyP : Try http://stackoverflow.com/questions/8009378/flash-light-not-enabling-in-samsung-mobile – Kartik Domadiya Dec 08 '11 at 13:18
  • 7
    for permissions,the correct code in the manifest file is : ` ` – ixeft May 24 '12 at 22:02
  • 1
    Also use :- camera.release(); – Chetan Gaikwad Aug 09 '15 at 11:34
  • How can I flash the light on and off? – Ruchir Baronia Apr 26 '16 at 04:58
  • Why is this `android.permission.FLASHLIGHT` undocumented? Is it safe to use it? I'm able to toggle the flashlight with camera permission only! – Muhammad Babar May 13 '17 at 15:06
  • It's deprecated – JPLauber Aug 20 '20 at 06:47
51

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();
    }
}
}
Jakub S.
  • 5,580
  • 2
  • 42
  • 37
  • 2
    What do you mean by "Usually front camera is at 0 position" ? How can I check which is in front and which isn't? BTW, front facing camera is the one that is directed to the current user. The back facing camera is the one that probably always has flash. And how can I check if the flash is turned on or off? – android developer Nov 25 '18 at 15:37
  • boolean b = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); This return boolean value of flash status – Ahmed Mohamed Aug 16 '20 at 18:00
  • Is there a way to check which of the cameras has flashlight capabilities, and also a callback for when a flashlight is turned on/off, and the state of each? – android developer Apr 26 '22 at 19:25
  • Yes, see my post below. Check if any of the CameraCharacteristic keys is FLASH_INFO_AVAILABLE – Rvb84 Aug 31 '22 at 08:14
35

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.

seliopou
  • 2,896
  • 20
  • 19
Ján Lazár
  • 491
  • 5
  • 8
13

I Got AutoFlash light with below simple Three Steps.

  • I just added Camera and Flash Permission in Manifest.xml file
<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.

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
9

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.

LukaCiko
  • 4,437
  • 2
  • 26
  • 30
  • 1
    The old android.hardware.Camera API continues to function exactly as before, so there's no fundamental reason you need to use android.hardware.camera2 for flashlight. It is possible that you can reduce power consumption and CPU load with camera2, though, as you don't need to keep an active preview to enable flashlight. – Eddy Talvala Jan 22 '15 at 05:32
  • I've tried one of the simpler implementations on two Lollipop devices and it didn't turn on the flash, even though it worked on all of several pre-Lollipop devices that I've tried it on. Perhaps that's just a bug in Lollipop. If the old methods still work for you and if you are not a Java purist continue using the old API as it is much simpler :) – LukaCiko Jan 22 '15 at 09:13
  • I currently have a Nexus 5 with Lollipop and it works perfectly. I also possess an application created by myself works and is implemented with these methods. In case anyone wants to try it. I put a link to play store: https://play.google.com/store/apps/details?id=com.fadad.linterna The important thing is mostly well ensure that the camera is active or disable before running the flash and permissions. – ferdiado Feb 14 '15 at 19:52
  • Sorry, my mistake. Another app was probably using the camera when I tried to turn on the flash with the old API. I've updated the answer. – LukaCiko Feb 14 '15 at 21:54
8

There's different ways to access Camera Flash in different Android versions. Few APIs stopped working in Lollipop and then it got changed again in Marshmallow. To overcome this, I have created a simple library that I have been using in few of my projects and it's giving good results. It's still incomplete, but you can try to check the code and find the missing pieces. Here's the link - NoobCameraFlash.

If you just want to integrate in your code, you can use gradle for that. Here's the instructions (Taken directly from the Readme) -

Step 1. Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
        repositories {
            ...
            maven { url "https://jitpack.io" }
        }
}

Step 2. Add the dependency

dependencies {
        compile 'com.github.Abhi347:NoobCameraFlash:0.0.1'
  }

Usage

Initialize the NoobCameraManager singleton.

NoobCameraManager.getInstance().init(this);

You can optionally set the Log Level for debug logging. Logging uses LumberJack library. The default LogLevel is LogLevel.None

NoobCameraManager.getInstance().init(this, LogLevel.Verbose);

After that you just need to call the singleton to turn on or off the camera flash.

NoobCameraManager.getInstance().turnOnFlash();
NoobCameraManager.getInstance().turnOffFlash();

You have to take care of the runtime permissions to access Camera yourself, before initializing the NoobCameraManager. In version 0.1.2 or earlier we used to provide support for permissions directly from the library, but due to dependency on the Activity object, we have to remove it.

It's easy to toggle Flash too

if(NoobCameraManager.getInstance().isFlashOn()){
    NoobCameraManager.getInstance().turnOffFlash();
}else{
    NoobCameraManager.getInstance().turnOnFlash();
}
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
  • Please add support for using Context instead of Activity. Thanks! – Vajira Lasantha Jun 30 '17 at 06:11
  • @VajiraLasantha The Activity object is required for taking the permission. I was planning to remove the requirement completely by separating the permissions somehow. It's been tracked here - https://github.com/Abhi347/NoobCameraFlash/issues/3 In the mean time, you can modify the code to remove the requirement if you want. I may need some time to work on it. – 0xC0DED00D Jul 03 '17 at 08:56
  • Yeah I saw that. I have already altered your lib to work with Context by removing permission stuff. Because my app already does permission validations. Please let me know when you released a proper implementation that supports Context. Thanks! – Vajira Lasantha Jul 04 '17 at 03:30
  • `You have to take care of the runtime permissions to access Camera yourself, before initializing the NoobCameraManager. In version 0.1.2 or earlier we used to provide support for permissions directly from the library, but due to dependency on the Activity object, we have to remove it.` – Pratik Butani Jan 04 '18 at 05:39
  • What if there are multiple flashes on the device? Some have on the front facing camera... – android developer Nov 25 '18 at 15:31
  • @androiddeveloper When I wrote the library, there was only one flash in the devices. Thus the library doesn't support multiple flashes. It can be updated to support it, but I currently don't have enough time for update and test the solution. The source code is there on GitHub. Feel free to test your solution and raise a PR. – 0xC0DED00D Nov 25 '18 at 21:15
  • @noob Do you know perhaps how to check which camera is front, which is back, and others? – android developer Nov 26 '18 at 07:35
  • Not sure, but each camera provides an id. The 0th camera is most probably the back camera and the 1st one is front camera. I don't know how it works out in dual back camera or even quad camera setup (The latest Samsung device), since I never tested the library on them. The actual code will depend upon which utility are you using for the flash functionality (There're 3 of them in the library). – 0xC0DED00D Nov 27 '18 at 02:46
7

Complete Code for android Flashlight App

Manifest

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

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

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

      <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name=".MainActivity"
              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>

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="turnFlashOnOrOff" />
</RelativeLayout>

MainActivity.java

  import android.app.AlertDialog;
  import android.content.DialogInterface;
  import android.content.pm.PackageManager;
  import android.hardware.Camera;
  import android.hardware.Camera.Parameters;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;

  import java.security.Policy;

  public class MainActivity extends AppCompatActivity {

      Button button;
      private Camera camera;
      private boolean isFlashOn;
      private boolean hasFlash;
      Parameters params;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          button = (Button) findViewById(R.id.button);

          hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

          if(!hasFlash) {

              AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
              alert.setTitle("Error");
              alert.setMessage("Sorry, your device doesn't support flash light!");
              alert.setButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      finish();
                  }
              });
              alert.show();
              return;
          }

          getCamera();

          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

                  if (isFlashOn) {
                      turnOffFlash();
                      button.setText("ON");
                  } else {
                      turnOnFlash();
                      button.setText("OFF");
                  }

              }
          });
      }

      private void getCamera() {

          if (camera == null) {
              try {
                  camera = Camera.open();
                  params = camera.getParameters();
              }catch (Exception e) {

              }
          }

      }

      private void turnOnFlash() {

          if(!isFlashOn) {
              if(camera == null || params == null) {
                  return;
              }

              params = camera.getParameters();
              params.setFlashMode(Parameters.FLASH_MODE_TORCH);
              camera.setParameters(params);
              camera.startPreview();
              isFlashOn = true;
          }

      }

      private void turnOffFlash() {

              if (isFlashOn) {
                  if (camera == null || params == null) {
                      return;
                  }

                  params = camera.getParameters();
                  params.setFlashMode(Parameters.FLASH_MODE_OFF);
                  camera.setParameters(params);
                  camera.stopPreview();
                  isFlashOn = false;
              }
      }

      @Override
      protected void onDestroy() {
          super.onDestroy();
      }

      @Override
      protected void onPause() {
          super.onPause();

          // on pause turn off the flash
          turnOffFlash();
      }

      @Override
      protected void onRestart() {
          super.onRestart();
      }

      @Override
      protected void onResume() {
          super.onResume();

          // on resume turn on the flash
          if(hasFlash)
              turnOnFlash();
      }

      @Override
      protected void onStart() {
          super.onStart();

          // on starting the app get the camera params
          getCamera();
      }

      @Override
      protected void onStop() {
          super.onStop();

          // on stop release the camera
          if (camera != null) {
              camera.release();
              camera = null;
          }
      }

  }
Raza Ali Poonja
  • 1,086
  • 8
  • 16
  • if the flash is already on before starting your example, then trying to turn off flash will not work... do you have a solution for that issue? – Taifun Apr 01 '17 at 17:35
2

A 2022 Kotlin version:

fun Context.isFlashLightAvailable() = packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

val Context.camaraManager: CameraManager get() = getSystemService(CameraManager::class.java)


fun Context.toggleFlashLight(on: Boolean) {
    camaraManager.run {

        val firstCameraWithFlash = cameraIdList.find { camera ->
            getCameraCharacteristics(camera).keys.any { it == FLASH_INFO_AVAILABLE }
        }

        firstCameraWithFlash?.let {
            runCatching { setTorchMode(it, on) }.onFailure { Timber.e(it, "Error setTorchMode") }
        } ?: Timber.e(Throwable("toggleFlashLight"), "Camera with flash not found")

    }
}

or with a suspending function that returns result

suspend fun Context.toggleFlashLightWithResult(on: Boolean): Boolean {
    return suspendCancellableCoroutine { cont ->
        runCatching {
            camaraManager.run {

                val firstCameraWithFlash = cameraIdList.find { camera ->
                    getCameraCharacteristics(camera).keys.any { it == FLASH_INFO_AVAILABLE }
                }

                val callback = object : CameraManager.TorchCallback() {
                    override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
                        super.onTorchModeChanged(cameraId, enabled)
            
                       if (cont.isActive) cont.resume(enabled)
                    }
                }

                if (firstCameraWithFlash == null) {
                    Timber.e(Throwable("toggleFlashLight"), "Camera with flash not found")
                    cont.resume(false)
                } else {
                    Timber.tag("~!").d("firstCameraWithFlash: $firstCameraWithFlash")
                    setTorchMode(firstCameraWithFlash, on)
                    registerTorchCallback(mainExecutor, callback)
                }

                cont.invokeOnCancellation { unregisterTorchCallback(callback) }
            }
        }
            .onFailure { Timber.e(it, "Error toggleFlashLight") }

    }
}
Rvb84
  • 675
  • 1
  • 6
  • 14
0

I have implemented this function in my application through fragments using SurfaceView. The link to this stackoverflow question and its answer can be found here

Hope this helps :)

Community
  • 1
  • 1
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
0

In Marshmallow and above, CameraManager's `setTorchMode()' seems to be the answer. This works for me:

 final CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
 CameraManager.TorchCallback torchCallback = new CameraManager.TorchCallback() {
     @Override
     public void onTorchModeUnavailable(String cameraId) {
         super.onTorchModeUnavailable(cameraId);
     }

     @Override
     public void onTorchModeChanged(String cameraId, boolean enabled) {
         super.onTorchModeChanged(cameraId, enabled);
         boolean currentTorchState = enabled;
         try {
             mCameraManager.setTorchMode(cameraId, !currentTorchState);
         } catch (CameraAccessException e){}



     }
 };

 mCameraManager.registerTorchCallback(torchCallback, null);//fires onTorchModeChanged upon register
 mCameraManager.unregisterTorchCallback(torchCallback);
aecl755
  • 340
  • 3
  • 15
0

Try this.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; // Usually front camera is at 0 position.
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
Jaswant Singh
  • 9,900
  • 8
  • 29
  • 50
-2

You can also use the following code to turn off the flash.

Camera.Parameters params = mCamera.getParameters()
p.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
belphegor
  • 483
  • 7
  • 10