Android Torch Light / Flash Light App Tutorial

Android Torch Light / Flash Light App Tutorial

In this tutorial we are going to learn how to create android Torch light / Flash light app. This is one of the common utility apps you find in Google Play. If you have wondered how to develop this android app or you want to code your own android torch light app, this tutorial is for you.

The concept behind android Torch light app is that the app makes use of the device camera Flash Mode to turn on and off the camera flash.

This will not work on a device that does not support any camera flash but we will have to put a check in place so that our app will not end up crashing.

Before we start, the first thing I will do is to list the environment and tools I used in this android tutorial but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidFlashLightApp

Package: com.inducesmile.androidflashlightapp

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

Manifest.xml File

Since we are going to access and make use of some hardware resources in our device like camera, we are going to use some android permissions. The list is as follows but note that you can remove the one you free is not necessary

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

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

<uses-permission android:name="android.permission.FLASHLIGHT"/>

<uses-permission android:name="android.permission.WAKE_LOCK"/>

The Wake lock android permission is use to keep the screen alive when using our app. The updated version of our project Manifest.xml file is shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="inducesmile.com.androidflashlightapp" >
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <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>

Activity_main.xml

Open the main layout of your project, Since I used the default Main Activity, my corresponding layout for this page is activity_main.xml.

We are going to add an Imagebutton View in the layout file. In your IDE you can choose the layout design view and drag and drop an ImageButton to the layout.

If you prefer to use code view, then copy and paste the code below into your layout file. As you can see the layout is very simple. We will use the ImageButton View to turn on and off our flash light.

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

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/flash_light"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/buttonoff"
        android:background="@android:color/transparent"
        android:contentDescription="@null"
        android:layout_marginTop="140dp" />
</RelativeLayout>

 MainActivity.java file

In the MainActivity.java class, we will instantiate the ImageButton by using the findViewById() method of the Activity class.

In order to fix the screen in portrait, we will call the method setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)  of the Activity class. Further more we will add a flag that will keep our app screen alive with getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)  method

In order to make sure that our app does do not use the Camera features in our device without first checking if our device supports Camera, we will use to following code to check if there is a flash light support in our device.

If there is none, we will use a Toast class to notify the use that the torch light will not work on the device.

boolean deviceHasFlash = getApplication().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

We will go further and create three private methods

1. turnOnTheFlash() – it is use to turn on the torch light

2. turnOffTheFlash() – it is use to turn off the torch light

3. getCamera() – use to return a Camera object

You can find the implementation of these method on the complete code of the MainActivity.java class below.

package inducesmile.com.androidflashlightapp;

import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    private ImageButton flashLight;
    private Camera camera;
    private Parameters parameter;
    private boolean deviceHasFlash;
    private boolean isFlashLightOn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        flashLight = (ImageButton)findViewById(R.id.flash_light);
        deviceHasFlash = getApplication().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        if(!deviceHasFlash){
            Toast.makeText(MainActivity.this, "Sorry, you device does not have any camera", Toast.LENGTH_LONG).show();
            return;
        }
        else{
            this.camera = Camera.open(0);
            parameter = this.camera.getParameters();
        }

        flashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isFlashLightOn){
                    turnOnTheFlash();
                }else{
                    turnOffTheFlash();
                }
            }
        });
    }

    private void turnOffTheFlash() {
        parameter.setFlashMode(Parameters.FLASH_MODE_OFF);
        this.camera.setParameters(parameter);
        this.camera.stopPreview();
        isFlashLightOn = false;
        flashLight.setImageResource(R.drawable.buttonoff);
    }

    private void turnOnTheFlash() {
        if(this.camera != null){
            parameter = this.camera.getParameters();
            parameter.setFlashMode(Parameters.FLASH_MODE_TORCH);
            this.camera.setParameters(parameter);
            this.camera.startPreview();
            isFlashLightOn = true;
            flashLight.setImageResource(R.drawable.buttonon);
        }
    }

    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                parameter = camera.getParameters();
            } catch (RuntimeException e) {
                System.out.println("Error: Failed to Open: " + e.getMessage());
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(this.camera != null){
            this.camera.release();
            this.camera = null;
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        turnOffTheFlash();
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(deviceHasFlash){
            turnOffTheFlash();
        }
    }

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

Save the file and run your project. If everything works for you, the project will appear like this in your device.

Android Torch Light / Flash Light App Tutorial

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

Add a Comment