Click here to Skip to main content
15,886,578 members
Articles / Mobile Apps / Android

Android Flash Light Application Tutorial Using Camera2 API

Rate me:
Please Sign up or sign in to vote.
4.20/5 (4 votes)
17 Jul 2016CPOL3 min read 32.6K   3   3
Android Flash Light Application Tutorial Using Camera2 API

In this article, we will explain how to create a free flashlight app for Android. This tutorial is part of Learn By Doing tutorial series, where we will show you how to create simple Android apps. This will be a hand’s on experience for beginners in the Android Development. After following this tutorial, you can create the best flashlight app for Android phones and distribute it through Google play.

Creating a New Project

Please follow the steps:

Android FlashLight Application

Add Minimum SDK

Choose Empty Activity Led Torch

  1. Open Android Studio and create a new project by going to File => New => New Project. Enter the Application Name as LedFlashLight and your company domain name. (We have used our company domain, i.e., androidtutorialpoint.com. Similarly, you can use yours.)
  2. Click Next and choose Minimum SDK. We have kept the default setting and click Next.
  3. Choose Empty Activity and click next.
  4. In the next screen, enter Activity Name as FlashLightActivity and remember to check the Generate Layout Button and then click Finish.

Enter Activity Name Led FlashLight

Gradle will sync the project and resolve all the dependencies.

Adding Permissions to Use Camera and FlashLight

Open your AndroidManifest.xml file and add the following permissions:

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

These uses-permissions tag tells the Android OS that our app will require access to CAMERA and FLASHLIGHT. Similarly uses-feature tells what features will be used in the app.
The Led Flash Light Application will only work in Portrait mode, so add the following in activity tag.

XML
android:screenOrientation="portrait"

The complete AndroidManifest.xml will be as follows:

AnroidManifest.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidtutorialpoint.ledflashlight" >
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.flash" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".FlashLightActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Apart from the package name, everything should be the same for you.

Generate Application Layout

Open activity_flash_light.xml and add the following code:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.camera2.MainActivity"
    android:background="#000"
    android:gravity="center">

    <ImageButton
        android:layout_gravity="center"
        android:id="@+id/button_on_off"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#000"
        android:src="@drawable/off"/>

</LinearLayout>

We are using an ImageButton. When the user presses this button, the Led Flash Light will be toggled.

Adding the Functionality

Open FlashLightActivity.java and declare the following variables.

FlashLightActivity.java

Java
package com.androidtutorialpoint.ledflashlight;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;


public class FlashLightActivity extends AppCompatActivity {

    private CameraManager mCameraManager;
    private String mCameraId;
    private ImageButton mTorchOnOffButton;
    private Boolean isTorchOn;
    private MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("FlashLightActivity", "onCreate()");
        setContentView(R.layout.activity_flash_light);
        mTorchOnOffButton = (ImageButton) findViewById(R.id.button_on_off);
        isTorchOn = false;

Here, we are just declaring the variables and in the onCreate() method, we are setting the layout for the activity. We are also referencing the mTorchOnOffButton Button from the layout. We will talk more about this in a while. Here we are using Camera2 API since Camera API is deprecated in Android now.

We need to detect whether the device has a Flash Light or not. In case the device doesn’t have support for flashlight, we have to alert the user through an alert message.

Add the following code below the above code in the FlashActivity activity.

FlashLightActivity

JavaScript
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        if (!isFlashAvailable) {

            AlertDialog alert = new AlertDialog.Builder(FlashLightActivity.this)
                    .create();
            alert.setTitle("Error !!");
            alert.setMessage("Your device doesn't support flash light!");
            alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", 
                            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // closing the application
                    finish();
                    System.exit(0);
                }
            });
            alert.show();
            return;
        }

If your phone doesn’t support camera flash, you will get the following error.
On pressing the OK button, the app will close.

Flash Not Supported Error Dialog Box

Next, we add the code to the onCreate() method to get the CameraManager object. Then, we set the OnClickListener() for the on/off button for our Led Flash Light Application.

In the OnClickListener(), we check whether the torch is currently on or off, then we call the turnOffFlashLight() to turn flash off in case the torch is already on and turnOnFlashLight() to turn flash on in case the torch is currently off.

Java
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            mCameraId = mCameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

        mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isTorchOn) {
                        turnOffFlashLight();
                        isTorchOn = false;
                    } else {
                        turnOnFlashLight();
                        isTorchOn = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

Next, we add the turnOffFlashLight() and turnOnFlashLight() methods for turning the Flash Off and On respectively. We will also add a method playOnOffSound to give the sound effect of clicking a button.

Java
public void turnOnFlashLight() {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, true);
                playOnOffSound();
                mTorchOnOffButton.setImageResource(R.drawable.on);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void turnOffFlashLight() {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mCameraManager.setTorchMode(mCameraId, false);
                playOnOffSound();
                mTorchOnOffButton.setImageResource(R.drawable.off);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playOnOffSound(){

        mp = MediaPlayer.create(FlashLightActivity.this, R.raw.flash_sound);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

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

In the turnOffFlashLight(), we turn off the Led Torch by setting
mCameraManager.setTorchMode(mCameraId, false);. Similarly, in the turnOnFlashLight(), we turn on the flashlight programmatically by setting mCameraManager.setTorchMode(mCameraId, true);.
In the playOnOffSound(), we use create() method of the MediaPlayer class to play the click sound.

At last, override the Activity Lifecycle methods by adding the following code. When the App is minimized by user, we will turnOff the Flash and as soon as the user returns to the App, the Flash Light will resume if it was on earlier.

Java
@Override
    protected void onStop() {
        super.onStop();
        if(isTorchOn){
            turnOffFlashLight();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(isTorchOn){
            turnOffFlashLight();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isTorchOn){
            turnOnFlashLight();
        }
    }
}

Now, run the app on an Actual Device, turn on flashlight and then use your own brightest flashlight app to find your stuff in the dark. You can download the Android flashlight app source code by clicking on the Download Now button at the top. You can also download the torch light apk by clicking on the Download APK above.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Hello Developer!

As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I hope you get the best possible value at of our platform. Stick with us for a while, and we promise you will become an $$Android Rockstar$$!

Android Tutorial Point is the right platform if you want to learn about android development. We have a broad collection of tutorials on different aspects of Android Development and it is growing rapidly. Here at Android Tutorial Point we thrive to deliver the best tutorials. In this direction, we are trying to create a community that will cater to your needs, whether you are a beginner or a seasoned veteran. For the beginners that are getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how to start with Android programming.


All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for latest android tutorials. You can reach out to us at our Facebook page https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at androidtutorialspoint@gmail.com

Comments and Discussions

 
Questionthis app is not working wit error "android.hardware.camera2.CameraAccessException: The camera device is in use already" Pin
Member 1197607015-Jun-17 3:17
Member 1197607015-Jun-17 3:17 
Questionnewbie needs sourcecode Pin
ParDHarD18-Mar-17 8:24
ParDHarD18-Mar-17 8:24 
AnswerRe: newbie needs sourcecode Pin
Member 1306859418-Mar-17 19:28
Member 1306859418-Mar-17 19:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.