How to turn on/off only camera flashlight – simple torch example

In this post, we are gonna develop a simple torch application which uses android device’s flashlight. Application will have only one button at the center of the layout which is used to turn on/off the camera flashlight.

When you press ‘Torch-ON’ button, our program calls system packages to turn on flashlight and the button text is changed to ‘Torch-OFF’ . Similarly when button is pressed again, it calls system packages again to turn off flashlight and changes the button text to ‘Torch-ON’.

Let us begin..

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Project] with project name FlashlightExample
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name
  • Click finish

Code Listings

Layout creation:

The layout.xml for this application should looks like below:

<?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-ON"  />
</RelativeLayout>

Application layout should look like this:

Create following objects and variables right under activity class:

//Set boolean flag when torch is turned on/off
private boolean isFlashOn = false;
//Create camera object to access flahslight
private Camera camera;
//Torch button
private Button button;

Refer button control and create PackageManager object as given below inside onCreate method:

//Refer the button control
button = (Button) findViewById(R.id.buttonFlashlight);
//Context object to refer context of the application
Context context = this;
//Retrieve application packages that are currently installed
//on the device which includes camera, GPS etc.
PackageManager pm = context.getPackageManager();

We should check whether the device has camera installed before we proceed with coding the logic to turn on/off the flashlight. Following code snippet checks whether camera is installed in your device or not:

if(!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Logger message
Log.e("err", "Device has no camera!");
//Toast a message to let the user know that camera is not
//installed in the device
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",Toast.LENGTH_SHORT).show()
//Return from the method, do nothing after this code block
return;
}

Create a new Camera object to access the first back-facing camera on the device:

camera = Camera.open();

Get the current settings for the Camera service:

final Parameters p = camera.getParameters();

Create listener class for the button which we created:

button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//yet to add logic to turn on/off the flashlight
}
});

Add turn on/off logic inside onClick method:

//If Flag is set to true
if (isFlashOn) {
Log.i("info", "torch is turned off!");
//Set the flashmode to off					
p.setFlashMode(Parameters.FLASH_MODE_OFF);
//Pass the parameter ti camera object
camera.setParameters(p);	
//Set flag to false				
isFlashOn = false;
//Set the button text to Torcn-ON
button.setText("Torch-ON");
} 
//If Flag is set to false
else {
Log.i("info", "torch is turned on!");
//Set the flashmode to on
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
//Pass the parameter ti camera object
camera.setParameters(p);
//Set flag to true
isFlashOn = true;
//Set the button text to Torcn-OFF
button.setText("Torch-OFF");
}

It is always good practice to release the resources that are hold by the application when it is no more needed:

@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}

You must add the permission  in AndroidManifest.xml:

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

[pglinkadssmall1]

Demo

We are done with coding, yet to test the application.

Right click on the project, choose Run as >> Android application:

Final output should look something like below:



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

Thanks for reading the post!.. If you feel this post is interesting, do share with your friends.. 🙂

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • ADARSH YADAV

    Hi,that was an awesome example and very helpful as well,on first hand i would like to thank you very much for the code & i appreciate your work dedication with android. I am using your this code because i am working with an application which is little bit copy of “https://play.google.com/store/apps/details?id=com.devuni.flashlight&feature=search_result” that app on Google play,please have a look on that and help me to code for other button which enable screen light.Thank’s in advance dude.

    Thanks & Regards,
    Adarsh Yadav
    Android Developer

    • adarsh yadav

      Sorry to intrrupt you again but the apk file of that project is not working…when i click on tun on button then there no flash light is opened and no action performed.

      • It is working in my device (Sony Xperia Android version 4 – Icecream sandwich). Please check whether your device has camera. As per the example, if your device doesn’t have camera or if it doesn’t support, a message “Your device doesn’t have camera!” will be displayed as soon as you open the application. Give a glance at the code and check what is not favoring you. 🙂
        Dig into the logs to find out the root cause.
        Share the error message if you are able to find from log message or console.

  • adarsh yadav

    yes I have Samsung galaxy R,my device has camera as well,actually I tried your apk first and when it not worked well then I downloaded your source code and import it and then again run it after that I used that new generated apk file and their is no error at log-cat and no error message on toast,everything is fully worked fine but when I installed apk it installed normally but when I clicked turn on button then their is no light on from my flash. I think you forget to put any permission. Please check it out because if you are creating any android application then it must work on every android device.

  • Nathan

    I have spent a significant amount of time trying to find this solution, I am terrible at java & I have an assignment due in a few days thanks for resolving my problem..! I just wanted to say that I am very grateful that you have shared this with the community, thank-you. If you manage to get this message it would be wonderful if you could share with me your E-mail or personal contact details, I am trying to build an application for a university assignment and it’s very tough.

  • Nathan

    Hello Android Guru;

    I am having a minor problem with the flashlight, why is it turning off after the orientation has changed? if you know a solution to my dilemma please let me know.

  • benjamin

    I was wondering if i could use this and make modification and add some stuff and share with my friends. I will not put it on the market but I would like to find a base of an app and try to add to it to make it fit my own needs. please email back and let me know?

  • Karan

    The Flash light of my Mobile (Micromax A116) doesnt work when using Camera app and Flash light app.
    The Camera takes the picture but without flash even though flash is on.
    And one more thing I am not seeing the built in Camera app in the Apps under all section.

    Please give the possible solution for this.
    Thanks

    • Flashlight will not work when Camera App is used. The reason is Camera app holds the Flashlight which is not available to other resources.

      • karan

        Thanks for your reply…
        I meant when I open the inbuilt camera app. click a picture the flash light doesn’t work.
        same way when I use flashlight app the torch light thing. the flash doesn’t work.

        I have seen camera app in the apps manager in my friends phone but I can’t see camera app in the apps manager of my phone.. it does appear in the menu though.please suggest/advise..
        thanks

        • Please check if flash feature is available. If flash doesn’t work even if the mobile device/tablet you are referring here has flash feature, please check with it’s manufacturer.

  • Rzenks mj

    The code is not working on nexus 3 (samsung three).
    i downloaded the apk file too and tried ,it didnt work.
    it only shows toast message when switched on and off.

    What could be the reason ,please can u explain this problem ?

  • david motanu

    tested on Samsung galaxy s3. is working.

  • Shoaib Ashraf

    hi, your code help me alot for my app.thank u.
    i want to control the intensty of flash light.can you help ma in that one.

  • Rami Sohail

    awesome tutorials one of the best android blog out there keep them coming

  • jony

    you app force close after click home and again run app this time your app force close

  • Application works without any issues. I tested in six devices so far. Get me the error message you are getting in logcat so that I can help you further.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares