Main navigation

Android Flash Light Application Tutorial Using Camera2 API

adsense

Adding Permissions to Use Camera and FlashLight

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

    <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

android:screenOrientation="portrait"

The complete AndroidManifest.xml will be as follows:

AnroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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 same for you.

Generate Application Layout

open activity_flash_light.xml and add the following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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.
If you are new to android development kindly go through the following tutorial to understand more about generating layout Basics of Android Layout

Adding the Functionality

Open FlashLightActivity.java and declare the following variables.

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

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

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.

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 method’s 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.

@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 you stuff in the dark. You can downlaod 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.



What’s Next ??

We will soon cover more tutorials under Learn By Doing !! section to provide hand’s on experience. Thanks guys for reading. If you have any doubts or suggestion then please leave comments in the comments section below . Subscribe to our website for latest Android Tutorials. Also do Like our Facebook Page or Add us on Twitter.


Reader Interactions

Advertisment ad adsense adlogger