Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Flash Light Application Tutorial Using Camera2 API

Android Flash Light Application Tutorial Using Camera2 API
In this tutorial, we will explain how to create 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 the 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.

We hope you have installed Android Studio. If you haven’t then follow the tutorial Installing Android Studio. and then return here. Also before going through this tutorial we suggest you make a simple Hello World App and run it on your smartphone. You can learn How to Connect, Configure App on Real Android device and Run Hello World program with Android Studio . So now let’s create our Led Flash Light Application. Start by creating a new project in Android Studio as follows.

Creating a new project

Please follow the steps:

  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.

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.

    

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

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

Generate Application Layout

open activity_flash_light.xml and add the following code.

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.

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.

CodeProject

The post Android Flash Light Application Tutorial Using Camera2 API appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Android Flash Light Application Tutorial Using Camera2 API

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×