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
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