Today i am going to demonstrate developing a simple android application. This application is about turning on and off device flashlight / torchlight with simple touch. Please note that this app is targeted to mobile devices only, i am not sure how this app looks in tablet devices.

Download Code
android developing torchlight application

Designing the application

This app contains not too complex design. You can design the application using graphic editor software like photoshop. Please find the PSD of the app in the source code folder of this tutorial. I am not covering the steps involved in designing the application as it is not the part of the tutorial.

Thanks to Keith Sereby for providing beautiful switch image. Check out his profile on dribble and twitter

Following is the screenshot of the app which we are going to develop in this tutorial.

android flashlight app tutorial

Resize and save each switch image in multiple dimensions for both on and off states. See the following image for your reference

android flashlight switch dimensions

Once you are done with designing part you can move to coding part by starting a new project.

Creating new project

1. Create a new project in Eclipse IDE by going to File ⇒ New ⇒ Android Application Project . I named my package as com.androidhive.flashlight and main activity as MainActivity.java

2. Open your AndroidManifest.xml file and add required permissions. I also disabled landscape mode in manifest file by using android:screenOrientation=”portrait” property.

android.permission.CAMERA – required to access the camera device
android.hardware.camera – required to access camera hardware features

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.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="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidhive.flashlight.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

3. Place all the switch image files under drawable-hdpi, drawable-mdpi, drawable-ldpi folders. I named switch image files as btn_switch_off.png and btn_switch_on.png

4. Create a new xml file named radial_background.xml under res ⇒ drwable-hdpi folder and paste the following code. This file is used to create radial gradient background for the app.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
            android:type="radial"
            android:startColor="#343030"
            android:endColor="#151515"
            android:gradientRadius="300"
            android:angle="270"
            android:centerY="0.3"/>
</shape>

5. Now open activity_main.xml file located under res ⇒ layout folder and type the following code. This layout file acts as main screen of the application.

In the following code first we applied a gradient background using radial_background.xml file which we created earlier. After that we placed an Image button with the switch image.

<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:background="@drawable/radial_background"
    tools:context=".MainActivity" >

    <ImageButton
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:src="@drawable/btn_switch_on"
        android:background="@null"
        android:contentDescription="@null"
         />   
</RelativeLayout>

6. Open your MainActivity.java file and do the following changes. Here we just declared required variables.

package com.androidhive.flashlight;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

	ImageButton btnSwitch;

	private Camera camera;
	private boolean isFlashOn;
	private boolean hasFlash;
	Parameters params;
	MediaPlayer mp;

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

		// flash switch button
		btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

}

Detecting whether device supporting flashlight or not

The important step is to notify user if the device doesn’t support flashlight by showing an alert message or some other means, then we’ll simply close the application.

7. Open MainActivity.java and add the following code. In the following code we are checking availability of the flashlight and if the device doesn’t support it, we’ll show alert dialog and close the application by calling finish().

		 /*
		 * First check if device is supporting flashlight or not
		 */
		hasFlash = getApplicationContext().getPackageManager()
				.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

		if (!hasFlash) {
			// device doesn't support flash
			// Show alert message and close the application
			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() {
				public void onClick(DialogInterface dialog, int which) {
					// closing the application
					finish();
				}
			});
			alert.show();
			return;
		}
android flashlight no flash support

Turning on Flashlight

8. Turning on flashlight can be done by setting camera flash mode to FLASH_MODE_TORCH. The following two functions getCamera() and turnOnFlash() will do that for us. Add these functions to your MainActivity.java file


	// getting camera parameters
	private void getCamera() {
		if (camera == null) {
			try {
				camera = Camera.open();
				params = camera.getParameters();
			} catch (RuntimeException e) {
				Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
			}
		}
	}

	 /*
	 * Turning On flash
	 */
	private void turnOnFlash() {
		if (!isFlashOn) {
			if (camera == null || params == null) {
				return;
			}
			// play sound
			playSound();
			
			params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_TORCH);
			camera.setParameters(params);
			camera.startPreview();
			isFlashOn = true;
			
			// changing button/switch image
			toggleButtonImage();
		}

	}

Turning off Flashlight

9. Flashlight can be turned off by setting flash mode to FLASH_MODE_OFF.

	 /*
	 * Turning Off flash
	 */
	private void turnOffFlash() {
		if (isFlashOn) {
			if (camera == null || params == null) {
				return;
			}
			// play sound
			playSound();
			
			params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(params);
			camera.stopPreview();
			isFlashOn = false;
			
			// changing button/switch image
			toggleButtonImage();
		}
	}

Finally call these functions in button click event

		 /*
		 * Switch click event to toggle flash on/off
		 */
		btnSwitch.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isFlashOn) {
					// turn off flash
					turnOffFlash();
				} else {
					// turn on flash
					turnOnFlash();
				}
			}
		});

Toggle switch images on flashlight on / off

10. When user touches the switch we need to toggle the switch image to on and off state just to indicate flashlight status. toggleButtonImage() has been called in turnOnFlash() and turnOffFlash() functions.

	/*
	 * Toggle switch button images
	 * changing image states to on / off
	 * */
	private void toggleButtonImage(){
		if(isFlashOn){
			btnSwitch.setImageResource(R.drawable.btn_switch_on);
		}else{
			btnSwitch.setImageResource(R.drawable.btn_switch_off);
		}
	}

Playing switch sound

If you are done with all the previous steps, your app will work perfectly. Here we can add an enhancement to our app by playing switch sound when user touches the switch. I downloaded two sound files from free sound libraries for switch on / switch off states and named them as light_switch_on.mp3 and light_switch_off.mp3

11. Under res folder create a new folder called raw and place these sound files in it. (res ⇒ raw ⇒ light_switch_on.mp3, light_switch_off.mp3)

12. Add the following function playSound() to your MainActivity.java file.

This function has been called in turnOnFlash() and turnOffFlash() functions.

	 /*
	 * Playing sound
	 * will play button toggle sound on flash on / off
	 * */
	private void playSound(){
		if(isFlashOn){
			mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
		}else{
			mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
		}
		mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }
        }); 
		mp.start();
	}

13. Importantly don’t forgot to release the camera once our app entered into background state as other apps might need to access camera. Add following code to your MainActivity.java file.

In onPause() method we turned off the flashlight as app entered in background state
In onResume() method we turned on the flashlight back again
In onStop() method we released the camera by calling camera.release() method.

	@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;
		}
	}

Setting the app icon

Finally design an icon for the app and place the image in drawable-hdpi (72 x 72 px), drawable-mdpi (48 x 48 px) and drawable-ldpi (36 x 36 px) folders.

Final Code

Final code of MainActivity.java is as follows

package com.androidhive.flashlight;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

	ImageButton btnSwitch;

	private Camera camera;
	private boolean isFlashOn;
	private boolean hasFlash;
	Parameters params;
	MediaPlayer mp;

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

		// flash switch button
		btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

	
		// First check if device is supporting flashlight or not		
		hasFlash = getApplicationContext().getPackageManager()
				.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

		if (!hasFlash) {
			// device doesn't support flash
			// Show alert message and close the application
			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() {
				public void onClick(DialogInterface dialog, int which) {
					// closing the application
					finish();
				}
			});
			alert.show();
			return;
		}

		// get the camera
		getCamera();
		
		// displaying button image
		toggleButtonImage();
		
		
		// Switch button click event to toggle flash on/off
		btnSwitch.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isFlashOn) {
					// turn off flash
					turnOffFlash();
				} else {
					// turn on flash
					turnOnFlash();
				}
			}
		});
	}

	
	// Get the camera
	private void getCamera() {
		if (camera == null) {
			try {
				camera = Camera.open();
				params = camera.getParameters();
			} catch (RuntimeException e) {
				Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
			}
		}
	}

	
	 // Turning On flash
	private void turnOnFlash() {
		if (!isFlashOn) {
			if (camera == null || params == null) {
				return;
			}
			// play sound
			playSound();
			
			params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_TORCH);
			camera.setParameters(params);
			camera.startPreview();
			isFlashOn = true;
			
			// changing button/switch image
			toggleButtonImage();
		}

	}


	// Turning Off flash
	private void turnOffFlash() {
		if (isFlashOn) {
			if (camera == null || params == null) {
				return;
			}
			// play sound
			playSound();
			
			params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.setParameters(params);
			camera.stopPreview();
			isFlashOn = false;
			
			// changing button/switch image
			toggleButtonImage();
		}
	}
	

	 // Playing sound
	 // will play button toggle sound on flash on / off
	private void playSound(){
		if(isFlashOn){
			mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
		}else{
			mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
		}
		mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }
        }); 
		mp.start();
	}
	
	/*
	 * Toggle switch button images
	 * changing image states to on / off
	 * */
	private void toggleButtonImage(){
		if(isFlashOn){
			btnSwitch.setImageResource(R.drawable.btn_switch_on);
		}else{
			btnSwitch.setImageResource(R.drawable.btn_switch_off);
		}
	}

	@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;
		}
	}

}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Egbert Dijkstra

    Thanks man, for all the awesome tuts, it helped me allot!

  • Rahim Sekkouti

    such a beautiful Tut, Thank you buddy 🙂

  • Mamro Kirill

    Excellent lesson… some ideas and this lesson were born will help.
    You could write still an example how to trace a call and to use processes (services)

  • Ramiz Mohamed

    Brilliant as always. The only gripe I have is that we have to wait in anticipation for the next one, 😉

    • I got little busy…. don’t worry i’ll update blog from now on ….

      • Jorge Casariego

        YEaaa!!! Excellent Ravi!

      • Ramiz Mohamed

        Lol, thanks for taking the time to reply. Your content is of such a quality and you have set quite a standard; that it is worth the wait.

  • Rajesh Tamada

    Great

  • Amir from Algeria

    thank you for your tuto amir from Algeria

  • Zuhry Fayesz

    superb tut brother …. ur tut always help me to experiment new in android and push the development beyond its limit … awesome again ..

  • Hassan Gillani

    thanks…Excellent work by Ravi 😉

  • Avtokluchi

    Great Tutorial, please show us how to track your phone on a webpage, i mean kind a gps tracker trough a website, THANKS!!

  • Hi Ravi nice to see u back and thanks for great post again as always

  • rank

    @ravi8x:disqus
    Great work man , as always..

  • Jomy P Jose

    Hi Ravi. How to make an animation like apple’s siri mic button.

  • Roney K

    Before developing Android Flashlight

    Android beginners need to learn more from basic

    So visit ANDROIDITUTS -Android Tutorials for beginners

    http://www.androidituts.com

  • chuck

    great tutorial! anyway, would you mind making a tutorial about android charts? Thanks in advance!

  • Manish

    nice tutorial….

  • Prasad

    Good one dude..:)

  • Omar

    please, how to convert it to widget???

  • Prashanna

    Thank you buddy. Awesome work. And lovely tut as well..Very helpful for android starter like me. Hope other tuts as well..and more over your descriptions and comments are appreciating… so Helpful to understand flow.

  • vikas .s

    nice tutorial.. can u pls giv a tut for colour flashlights……

  • Figo

    Hi this part does not work in my example:

    if (!hasFlash) {
    // device doesn’t support flash
    // Show alert message and close the application
    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() {
    public void onClick(DialogInterface dialog, int which) {
    // closing the application
    finish();
    }
    });
    alert.show();
    return;
    }

    • Aquilla

      The method setButton(CharSequence text, ClickListener) is deprecated, try the same method with this params: setButton(AlertDialog.BUTTON_POSITIVE, text, ClickListener);

  • Richard

    Hello — I just found your tutorials. I am anxious to learn from them.

    I just downloaded and compiled the App through AIDE (free version). The App installs and starts just fine, but the camera light does not turn on or off. I have a Droid X. I have an App called LED Light that does work, so my hardware appears to not be the issue.

    Do you know what the issue might be? Thanks, Richard

    • JIN

      did you try to remove LED Light and then try to run it ?

  • Giolaoit

    Thank you !

  • remmersd
  • hytham

    nice work

  • Mamro Kirill

    Galaxy Nexus doesn’t work!

  • Adnan Nazir

    like always such a helpful tutorial.. Ravi can you upload a complete tutorial of retrieving contacts from gmail and send them message?

  • Faraz Ahmad Khichi

    Hey … i want help i made an flashlight widget … but light turns off when screen turns off …. plz help me out

    • ritesh

      use wakelock , screen will not turn off till app is having focus

      • Faraz Ahmad Khichi

        i m using widget … not an activity

  • Rajendra Maharjan

    alert.setButton(“OK”, new DialogInterface.OnClickListener()

    i got problem on this line … says setbutton is deprecated ..
    plz can any one say what is the problem ??

    • Shantanu Patel

      use alert.setButton(AlertDialog.BUTTON_POSITIVE,”OK”, new DialogInterface.OnClickListener()

      hope this can help…

      • Guest

        alert.setButton(AlertDialog.BUTTON_POSITIVE,”OK”, new DialogInterface.OnClickListener()

        public void onClick(DialogInterface, int which) {

  • ritesh

    Hi ravi , it is not working on my motorola defy+ . Following error messages are coming in logcat:
    CameraSettings Param type 50 not supported
    CameraSettings Param type 51 not supported
    CameraSettings Param type 53 not supported

    Please help me out..
    Thanks in advance

  • KhinMoe

    Thanks for your great tutorial 🙂

  • Omar Zaki

    Thank you very much

  • Roney Kakkanatt

    Android SQLite Database Insert Example Tutorial

    http://androidituts.com/android-sqlite-database-insert-example/

  • Steve

    Awesome Tutorial!!! Made a few tweaks (Made it vibrate instead of playing a sound) Please keep them coming.

  • Borislav

    package R does not exist ? HELLPP PLease
    And also setContenView doesn’t work

  • Bkmz

    Great thanks! Helped me tot find an error in my own code)

  • Rajendra Maharjan

    why it is not working on google nexus ??

    • Steve

      I had the same issue on my Nexus 10, everything worked great on my HTC One so I knew it was a device issue and started searching and I found a fix.

      Import…

      import android.view.SurfaceHolder;
      import android.view.SurfaceHolder.Callback;
      import android.view.SurfaceView;

      Add the following to onCreate

      sView = (SurfaceView) findViewById(R.id.PREVIEW);
      sHolder = sView.getHolder();

      Add the following to the XML layout above the ImageButton

      • Thanks Steve 🙂

      • Rajendra Maharjan

        Thnx 🙂

      • Sumit Vairagar

        Also add this code in the turnFlashOn()

        camera.setPreviewDisplay(sHolder);

      • Rocky

        It stopped when app opened

  • sasi sereen

    hello, thx for this amazing tut but i did the code and there is no error at all but when it run on my mobile nothing happens just a button with sounds ,, it does not turn the flash light on or off .. why?? :((

  • Keng Lang

    Hi Ravi. How to make effect strobe flashlight ?

  • Ajay Prasad

    Hi,

    this is a great example, but i have a question can flashlight work as a projector light please reply me with a example.

    Thanks

    • NO

      • Ajay Prasad

        Hi Ravi,

        Thanks for your reply, if you don’t mind can you tell me the reason behind that “NO”.

        • Projector needs a special hardware, we can’t project something using flashlight.

      • ATTAULLAHKHANKTK

        sir is there any way to use the mobile screen which displays on the projector just as like computer screen displays…………

  • Rami Masarweh

    thanks man

  • Steve

    I found another Trick… To always keep the Flashlight On (Not allowing the screen to timeout) add the following.

    Import..
    import android.os.PowerManager;

    Add the Following to the onCreate(… )
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, “DoNjfdhotDimScreen”);

    Add the following to onPause() after super.onPause()
    wl.release();

    Add the Following to onResume() after super.onResume();
    wl.acquire();

    Add the following permission to the manifest

    • json

      is not work with me in galaxy s2 android 4.1.2

  • Chris Barnett

    Another way to stop the screen timeout is to add the following to your onCreate() method:

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    This doesn’t require any extra permissions. See this recommendation in the Android docs: http://developer.android.com/reference/android/os/PowerManager.html#FULL_WAKE_LOCK

  • sampath

    Excellent tutorial. Very easy to understand. Thank you very much for this.

  • Ted Kayne

    Great TuT! But I have a question. What do I need to do that the flash light keeps on (after turnig it on) if I press the home button on my device?

    Can anyone help me pls?

    I’m looking forward to your help!

    • Tuur Neckebroeck

      You have to delete the overridden void onPause() because you have called the void ‘turnOffFlash()’. So when you close the app, it turns off the flash.

      • Ted Kayne

        Hmmm… Sorry but this doesn’t work the way I actually wanted…
        1. The flash turns already on, when I open the app and 2. the flash turns off after I pressed the home button.
        What I want is exactly the oppsite of this two points.

        Oh and I added “turnOffFlash();” to the overridden void onStart() and replaced turnOnFlash(); with turnOffFlash(); in the overridden void onResume() because I don’t want that the flash turns on when I open the app.

        Any other suggestions, please?

        Thanks in advance!

  • jason

    Thanks for the tut, but I have a question, my flashlight won’t light up when I pressed the button. (all the codes are identical to the tut’s)

    • google

      you need to implement a surfaceview in your “flash on” method, then make its callback…..check a few posts below

  • krishna bhatta

    Camera.open shows error on getCamera method. Any Helps please

  • Shashidhar

    Plz help
    i dont get any errors in eclipse , but after i install the
    app on phone when i open the app , i get an error message “Unfortunately
    the com.androidhive.flashlight has stopped “

    • Duy Nguyễn

      Please post you logcat.

      • fede_rico

        Hello, I think I have the same problem. Here are the interesting lines of my logcat. Thanks in advance for your help.

        04-22 09:34:20.297: W/dalvikvm(1244): threadid=1: thread exiting with uncaught exception (group=0x41465700)

        04-22 09:34:20.307: E/AndroidRuntime(1244): FATAL EXCEPTION: main

        04-22 09:34:20.307: E/AndroidRuntime(1244): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lux/com.example.lux.MainActivity}: java.lang.NullPointerException: println needs a message

        • Duy Nguyễn

          I think you should delete this sentence Log.e(“Camera Error. Failed to Open. Error: “, e.getMessage());

          • fede_rico

            Thanks. I tried but the problem remains. I deleted some parts to see where the problem may be, and found out that the app works if I delete the content of

            if (!hasFlash) { … }

            Now that I found the error I’m a bit embarrassed… as you can see in the “final code” above, the following line was too long and was cut in two lines and the .create is on a new line. I removed the line break and everything worked.

            AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();

            So if somebody has the same problem, first check if the code has strange line breaks. Hope this helps.

          • Duy Nguyễn

            I really happy because it worked with you, good luck.

  • Luuk Janssen

    First of all, thank you very much for this tutorial. I want to learn programming code for Android applications and this tutorial is very helpfull in understanding the basics. I have a question tho:

    The image button has a very short delay in displaying the image for the off state and visa versa the on state. The flash turns on/off immediately, the sound is played directly, only the new image button switches a few milliseconds later. Is there a way to make that image switch faster?

  • Kashan Zahid

    downloading problem..any alternate link from where i download complete application

  • haroon

    Good demonstration ever seen
    Thanx

  • Vinícius B.

    Can anyone explain how do I do to not turn on the flash automatically when the app is started?

    • tweedledum

      set isFlashOn to “true” and insert btnSwitch.setImageResource(R.drawable.btn_switch_off); after setOnClickListener in onCreate

    • Kiprop Korir

      Disable it on the on start method 🙂

  • Mushfiqur Rahman

    Hello, I really like the tutorial, its in very detailed manner. But I am facing a problem, that is when ever I try to put void method it gives an error in eclipse. For example: “private void getCamera()’. Please help!

    • Islam Fekry

      try to make it auto complete from the block code and move it to the suitable place

  • Anand

    can someone send me a link to the eclipse IDE needed for download

  • Ryan Mattox

    hey guys, running the debug and getting a error: cannot find symbol method turnOnFlash()

    In this code:

    // Switch button click event to toggle flash on/off

    btnSwitch.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    if (isFlashOn) {

    // turn off flash

    turnOffFlash();

    } else {

    // turn on flash

    turnOnFlash();

    }

    }

    });

    }

  • Guest

    The led is not Working in kitkat version :(,.., plss need help

  • Rims Jain

    the sample of ur code is not wrong with kitkat version as LED is not turning wen d button is clicked,.,plsss need help as soon as psbl. 🙁

  • Fatih

    heyy.

    i m new on android.

    i have a problem making this app.
    Here;
    setContentView(R.layout.activity_main);
    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
    mp = MediaPlayer.create(Flashlightt.this, R.raw.light_switch_off);
    mp = MediaPlayer.create(Flashlightt.this, R.raw.light_switch_on);
    btnSwitch.setImageResource(R.drawable.btn_switch_on);

    all of them, R. is the problem.
    what can i do?

    • youming2007

      It could be problems with your resources. R is a generated file, it’s OK only if your resources are built without any errors. If you are sure your resources are OK, just delete R file (maybe restart your IDE if there are still errors) and Android will generate it automatically.

    • Adrian Deac

      Hi, I had the same problem. You need to create a folder named “raw” into the “res” folder, then copy the two mp3 files (light_switch_on and light_switch_off) into the “raw” folder.

  • gaurav

    how do i keep it on when the screen goes blank?

  • Alexander Fedulov

    Subscription to your channel does not work. No emails are being sent. Please check on this.

  • Wing

    Note that on the Nexus 5 (and some other phones), you have to:
    camera.setPreviewTexture(new SurfaceTexture(0));

  • Parthiban

    In which method do we need to add the line camera.setPreviewTexture(new SurfaceTexture(0));

  • DroidNoob

    Would it be possible to get the full source code modified to work with the Nexus 5 ? I’ve read the comments below but I don’t really get where to add the lines, I have some errors with Eclipse whenever I try…

  • It asks to create “constant” or “field” for (R.id.btnSwitch) what to do?

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    //flash switch button

    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

    }

  • Pooja

    i am also have problems running this code with nexus 5 . can someone please help me

  • Thank you so much for such a useful tutorial.

    I have created a flashlight app ‘Moto Torch’ specially for Moto G with the help of this tutorial. Its working perfect on Android Kitkat. You can go to the link below and download this app.

    http://www.techcareonline.in/2014/09/moto-torch-free-android-flashlight-app.html

    Thanks again!

  • deniz

    i cant turn off the light. i download the code but the image turns off but light still turn on
    .How can i solve?

  • Ali

    Hi Ravi, Its a nice tutorial indeed.Can you give me idea how to keep the flash on in these states?
    (1) App is paused.
    (2) App is on forground and power button is pressed.
    (3) Backpressed while app running.

  • neel

    it is not working on nexus 5 mobile. this is bullshit application.

    • Saravana

      Dai…Neel mandaya…If its not working for you..u cant say its a bullshit application. Check when is this created, its created on 2013. Don’t blindly copy and paste. Try debugging and find out whats the problem and whether API is changed or not. Adhae vittu tu..pikkali thanamae comment vera…

  • Ashish Tiwari

    HI Ravi, I am trying to develop an app that could work like a torch app, just for learning but, the flash list and camera is not detected. I used same feature and permissions in manifest file as you have used here. I have downloaded your code also but it is showing “Sorry, your device does’t support flash light”. Please give some idea how can I do it. One thing more that I should tell you is I am using “Karbonn” device. It has camera & flash but I am not able to detect them. I downloaded Flashlight app from play store and it is working great… =D .. Please suggest

  • Prateeksha Singh

    Hi Ravi,
    Great example. 🙂
    Could you please give a sample for the same app using class Camera2?
    I had built a similar app using Camera class, but on API 21, it says that Camera is now deprecated. Please guide me on how to use Camera2.
    Thanks.

    • karampal

      Hi….
      I have same problem if you find the sol. please help me…..

    • Sepehr Shamsaei

      the same problem too 🙁

  • Vincenzo

    Hi, this is a Great Tutorial, Congratulations Ravi
    I Have a questions, if I wanted to to open a Ledflash camera without button o button image (without event click). For example When the activity start on automatic led on ? How I can do this? thank so much

    • Roshan

      for this you instead of writing your code into the onClickListener you have to write the code into the onCreate() method. This will enable the flash as soon as the activity is started.

  • Vivek Bhardwaj

    Hello sir ..! it was an amazing tutorial ..

  • Yashwanth

    Hi all,
    Iam getting the camera 1001 error in the log cat when the flash light is on and the error is reapeating for every 7 to 10 secs….please help me..

    Thanks,
    yashwanth.

  • maharshi neela

    What should we write in the refs.xml?? Please let me know asap. Im having an error in this file refs.xml

  • wow, really it’s a very useful tutorial for Newbies to understanding how android applications are work in behind the screen.
    i also a newbie on app development and this tutorial is very helpful for me 🙂
    but i have a Question? which is:
    when i open this application the flash light will automatically active.how can i deactivate this flash light while application is open. i just want to active and deactivate the flash light when user click on the button.
    Thanks.

    • HaX

      onResume should be like this :

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

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

  • hello can some one please help me to……
    how do i keep flashLight on when the screen goes blank?

    or when I clicking on Lock Button..

    • Sukheshkumar

      Hello Sir.. Did you got solution for the problem.? I am also facing the same problem.. Flash Light turns off when the screen is locked.. Plz let me know if you have found solution for this problem.. Thank You.

  • Thtcoolkid 14

    I have a question, my android studio cant resolve the setOnClickListener or View v. even though i tried importing both the views, any help?

  • Kerollos

    I need help please! I need the background to change from black to white when I click on btnSwitch ?

  • vishal Kushwaha

    Flash light is off after some time when the screen goes black, But i want that flash is still on untill i press the button.

    • Bilal Ahmed

      instead of this

      protected void onPause() {

      super.onPause();
      // on pause turn off the flash
      turnOffFlash();

      }

      Do this:

      protected void onPause() {

      super.onPause();
      // on pause turn off the flash
      turnOnFlash();

      }

      • Ramesh Bista

        This doesnot works for me bother.I want my flash to turn on background too

        • Abu Nayem

          then you should use service.

  • Ashenafi Fasil

    i need help plzz
    camera = Camera.open();
    params = camera.getParameters();
    coudnt worked what can i do?

  • Willie Botha

    I found that with some devices using camera startpreview and stoppreview everytime makes the flashligh not respond after a while. And if you take it out, devices like Samsung does not work at all. To get past this I used startpreview when my activaty starts and when it stops I use stoppreview on the camera object. This solves the problem for me.

  • Trimbak Jaiwal

    Hello I’m new to android
    plz help me
    how to run this project
    I downloaded this project
    plz help

    • QuestLima

      i think u will need Android SDK yes like Android Studio just google it but
      you must know at least basic java programming. Thank you.

  • Tony

    Thank! very helpful

  • Akashdeep Singh

    This code is not working on API 23, how to deign seprately for it

    • Abdul Rehman

      yes im too whats is solution Akashdeep Singh ?

  • Prathap

    how to control the sound method by toggle button….if the state is OFF ..that shld disable sound and vice-versa…

  • Arnold Parge

    I am unable to tun my app.
    it gives me error “failed to connect to camera service” in getCamera() method.
    Please help..

  • samim reza 570

    thanks i thing it help me .

  • Pulkit Khullar

    hi , thanks for the grate tutorial but the code is not working.

    alertDialog.setButton(“OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    // closing the application
    finish();
    }
    });

    code mentioned above is showing error.Need Help.

    Thanks.

  • Akshay Sudhakaran

    please give project zip file

  • Pulkit Khullar

    hello everyone , i just found the solution for the alertDialog.setButton error solution.

    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,”OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    // closing the application
    finish();
    }
    });

    DO THIS AND THEN EVERYTHONG IS GOOD..!! 😀

  • Tango Test

    I am using surfaceview and camera.Params

    private CameraSource cameraSource;
    private SurfaceView surfaceView;

    surfaceView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    surfaceView(cameraSource, camParams.FOCUS_MODE_CONTINUOUS_VIDEO);
    }
    });

    this code for Auto focuse only. Now i want to turn on/off flash light using button with camera preview.
    now i want to turn on/off Flash light on same time.

    try {
    Camera camera = (Camera) field.get(cameraSource);
    if (camera != null) {
    Camera.Parameters params = camera.getParameters();
    params.setFocusMode(focusModeContinuousVideo+Camera.Parameters.FLASH_MODE_TORCH);
    camera.setParameters(params);
    return true;
    }

    return false;
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    }
    give some idea how to do. what was the mistake in this code

    at android.hardware.Camera.native_setParameters(Native Method)
    at android.hardware.Camera.setParameters(Camera.java:1979)

  • Sukheshkumar

    Flash Light turns off when the screen is locked.. How to avoid this..?

    • Pramod Baggolli

      you may use service for that …….

  • Fahim Khan

    this whole bunch of code is not working for me i think some new version of code will work

    • Might be. It’s very old tutorial.

      • Fahim Khan

        Sorry now it’s working I have to manually import the packages and permission so now it’s working thank you very much I’ll follow your every tutorial thank you very much for this.. 😁😀

  • 葉光庭

    It’s WORK!!!!!!!!!!!!!

  • Bhupender Sharma

    This code is not working in marshmallow and nougat. PLZ tell me what i do for run torch in marshmallow.

  • can any one tell me how to add shaking functionality for turning on and off the flashlight ?

  • mak

    hi i have query is ” Multiple markers at this line
    – Syntax error on token “void”, @ expected
    – Syntax error, insert “enum Identifier” to complete
    EnumHeaderName
    – Syntax error, insert “EnumBody” to complete BlockStatement
    – Syntax error, insert “EnumBody” to complete BlockStatement
    – Syntax error, insert “enum Identifier” to complete
    EnumHeaderName”

  • mak

    please what is solution of this error “Syntax error on token “void”, @ expected” when we use private void use at that time occure

  • awais

    can anyone tell me how i manage light animation on bloodpressure meter
    plz

  • ele uni

    hi thank u @ravi8x:disqus for your tutorial do u know how can i connect on/off key with my volumes?
    I searched about it and i found this code what should i enter instead of “do your thing”

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
    // Do your thing
    return true;
    } else {
    return super.onKeyDown(keyCode, event);
    }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
    if (action == KeyEvent.ACTION_DOWN) {
    //TODO
    }
    return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
    if (action == KeyEvent.ACTION_DOWN) {
    //TODO
    }
    return true;
    default:
    return super.dispatchKeyEvent(event);
    }
    }

  • Naaz Tabi

    Can i use this Source Code On Google Playstore …. Reply me ASAP
    .

    • Nope

      Nope

      • Abdul Rehman

        why? we not use Nope plz give detaiil

  • Kennedy

    is there a way to control intensity(e.g, control how bright the light may be)

  • AndroidLearner

    I am a complete noob.So this is my question android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class. In this tutorial we are using camera class.So what is the new corresponding command or could you please comment what all those command do.One in Main Activity. Help will be appreciated.

  • sangeeth

    if my flash was in on mode and went to onPause it should be in on only,

  • Avinash Reddy

    how to get the dialogue box for camera permission ,my app works only by giving permission manually to camera

  • Hariom Sinha

    i am gtting runtime exception, and i have given all the permissions in my marshmellow device

    • Abdul Rehman

      yes im too whats is solution

  • asad ullah

    this is half script some .XML file is not finded here