Main Tutorials

How to turn on/off camera LED / flashlight in Android

In this tutorial, we show you how to turn on/off the phone camera led or flashlight in Android. See code snippets :

1. Turn on


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

2. Turn off


	camera = Camera.open();
	Parameters p = camera.getParameters();
	p.setFlashMode(Parameters.FLASH_MODE_OFF);
	camera.setParameters(p);
	camera.stopPreview();

And, put following permission on AndroidManifest.xml.


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

P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).

1. Android Layout

A button only.

File : res/layout/main.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" >

    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       	android:layout_centerVertical="true"
       	android:layout_centerHorizontal="true"
        android:text="Torch" />

</RelativeLayout>

2. Activity

Read the code, a button to turn on / off the flashlight, it should be self-explanatory.


package com.mkyong.android;

import android.app.Activity;
import android.content.Context;
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.view.View.OnClickListener;
import android.widget.Button;

public class FlashLightActivity extends Activity {

	//flag to detect flash is on or off
	private boolean isLighOn = false;

	private Camera camera;

	private Button button;

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

		if (camera != null) {
			camera.release();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

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

		Context context = this;
		PackageManager pm = context.getPackageManager();

		// if device support camera?
		if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Log.e("err", "Device has no camera!");
			return;
		}

		camera = Camera.open();
		final Parameters p = camera.getParameters();

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if (isLighOn) {

					Log.i("info", "torch is turn off!");

					p.setFlashMode(Parameters.FLASH_MODE_OFF);
					camera.setParameters(p);
					camera.stopPreview();
					isLighOn = false;

				} else {

					Log.i("info", "torch is turn on!");

					p.setFlashMode(Parameters.FLASH_MODE_TORCH);

					camera.setParameters(p);
					camera.startPreview();
					isLighOn = true;

				}

			}
		});

	}
}

3. Android Permission

Assign CAMERA permission.

File : AndroidManifest.xml


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

    <uses-sdk android:minSdkVersion="10" />

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

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FlashLightActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

4. Demo

None, until i have 2nd hand phone to capture the current flashlight on my phone 🙂

Download Source Code

Download it – Android-LED-FlashLight-Example.zip (16 KB)

References

  1. Android Camera Javadoc
  2. Android camera Parameters Javadoc

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
42 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Shravan kumar yadav
6 years ago

Hello sir
How to make online examination system in android.
Please help me

achref
5 years ago

when we open the flashlight , camera is blocked ..
how can I open flashlight and camera at same Time ?

zubair khan shinwari
6 years ago

Thanks u so much dear sir

Okwuchukwu Cyril Ohakwe
7 years ago

please am having some little problem in my coding i don’t know if it is from my android studio setup or the way i code it,
if i type in your code by my self into my androidManifest.xml it will show me red on some code saying can not resolve
it happen on this codes:
camera = Camera.open();
final Parameters p = camera.getParameters();

p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();

the .open(), .getParameters(), .setParameters();, .stopPreview();
this are the code that will be coloured with red saying can not be resolve etc
and if i copy past it they will all be OK. but the R will be saying can not be resolve why
please and solution.

Sandip
7 years ago

May be u’ll need to import the camera class file., then all of its methods can be resolved.

Ashish Shetty
9 years ago

When i go back from the application of flashlight the light will by still be ON (i mean to say that torch app will still be running in the background).How to stop this session when i go back from this app?

Sara M
9 years ago

Could I use this for a front facing camera to show the LED Lights for notifications instead?

doyeob
9 years ago

awesome example!

Avery
10 years ago

Thank you for creating this tutorial. It’s my first app (besides “hello world”). It works well on my Galaxy S2.

Andrew
10 years ago

Thank you! This was very helpful.

Jacob
10 years ago

Alright I’m Just done with this. I don’t know how to use that codeing
I have a keyonca echoand when I try a flashlight
App it just flashes. I need a constant beam not a strobe!

Danilo
10 years ago

the app run but the flash don’t work

vaibhav
10 years ago

How to turn flash led without opening camera ..
Actually i am making an led torch app in android and i want to turn flash on without opening camera so is it possible to make such an app???

Waiting for ur reply
Thanxx

alina
10 years ago

I have to turn on camera flash using openCV. I need to use NativeCameraView but it doesn’t work.

alina
10 years ago

can I open the flash using NativeCameraView in opencv? I tried but it doesn’t work.

memorial day picnic recipes
10 years ago

Good answer back in return of this query with solid arguments and describing the whole thing concerning that.

Help Desk Support Software
10 years ago

What’s up friends, how is everything, and what you want to say concerning this piece of writing, in my view its in fact awesome designed for me.

choe yong seok
10 years ago

really thanks for your help 😉

Nidia Dudzik
10 years ago

If you have recently lost or broke a flashlight, or if you are in the market for a new, better brand, then you are probably facing a lot of decisions about what kind of flashlight to purchase, and what will work best for your various needs. LED flashlights have risen in popularity, as have batteryless flashlights. :”

With best thoughts
<http://www.melatoninfaq.com/

Lois Langstaff
10 years ago

The digital age has taken the world by storm, with the introduction of the camera phone, photo digital imagery tools are at the fingertips of consumers today because they are built-in to low end and high end styled cellular devices that are the rage with American all over the country.’

Go and visit our very own website too
<".http://www.caramoanpackage.com/caramoan-tour/

kiri
11 years ago

Hi,
I am new to android and have an issue with my GT-N7100 phone that force closes whenever I start the camera app. Any camera flashlight app also does not run and closes with error. I believe some app or firmware is missing or corrupted on my phone. Code to check camera firmware version also force closes with error. Since you seem to be an expert on the android environment, was wondering if you could help point me to where to looks for the necessary files to be able to operate the camera and flash. Thanks in advance.

ibad ur rahman
11 years ago

Not work on Samsung glaxay. not the torch is on and not off. just a buuton on screen is show.

kikesainz
9 years ago
Reply to  ibad ur rahman

Try to write this line:
camera.setPreviewTexture(new SurfaceTexture(0));

after this one:
camera = Camera.open();

This one requires API 11, so you should have this line in AndroidManifest.xml

See:
http://stackoverflow.com/questions/9505945/led-flashlight-does-not-work-on-samsung-galaxy-nexus

Mathew
11 years ago

Hi,

I have noticed that method does not working on Motorola Razr/Droid Razr under ICS.
Any ideas how to fix it?

Sabbib
11 years ago

Hi i tried this on both avd and my galaxy s3. In my s3 it doesn’t install. and in the avd it doesn’t support flashlight. my s3 is 4.0.4, i adjusted the minSDK to 13 and Target to 14, still doesnt install. what am I doing wrong

khaleel D Tonnimeeran
11 years ago

Really u r an expert who can solve mind blowing problems.. I will keep asking u more stuff in the future.. Thank u for ur support.!

Sabba
11 years ago

Hello Mkyong;
Please contact me 🙂
I have tried my best to follow your tutorial about using the camera LED as a flashlight but the problem I am having is with the device support, I would like for it to being once the user has clicked the torch. By default the code you have made checks to see if the device has a LED as soon as the application begins which isn’t my objective, could you please tell me how I could make an alert message for users that don’t have a built-in LED as soon as they have clicked the button “torch”..? I am totally hopeless at java & I know that you’re a busy person but this needs to be resolved urgently. If you would like more detailed information about the problem please send me a message through Facebook, I would more then happy to provide you with a short video of the application running on a real device which could explain the problem in more depth.

Here is the tutorial page that I am having trouble with: https://mkyong.com/android/how-to-turn-onoff-camera-ledflashlight-in-android/

I hope to hear from you soon,
thanks.

Sabba
11 years ago
Reply to  Sabba

Udhay solved my problem thanks anyway!

vikram raj
11 years ago

i get error when i run this application in emulator that unfortunatly FlashCamera has stopped…
please help me to solve this……..

Rohit
11 years ago

hi..can u plz tell me how to create a widget for flashlight that works in all phones
i made one but its only working in samsung handsets not in lg..
plz help me

Ahmad
11 years ago

You are an expert
This is the shortest and simplest code Ever for a flashlight
THANK YOU !!!!!!!!!!

Udhay
11 years ago

I would like to say thank you for the wonderful explanation. I have created simple ‘Torch’ application using the same idea here:
http://android.programmerguru.com/android-flashlight-example/

Sabba
11 years ago
Reply to  Udhay

Hi Udhay thanks so much for uploading that, I have spent hours trying to solve a problem that you managed to complete.. thanks dude 😀 you have saved my ass.

MobileThemesWorld
11 years ago

Thanks for sharing this tutorial