How To Make Flashlight Application in Android Studio

 Make Flashlight Application In Android :

Today, Our post is How to make flashlight app using the android studio. In this post, we will create flashlight app for android mobile using an android studio with step by step. Therefore, If you will follow my guideline with carefully so you will make your own android flashlight app with easy.

Step 1: Manifest.xml in the android studio:

First of all, you need camera permission in Manifest.xml file to make flashlight app. Therefore, we will add some camera permission in our Android studio manifest.XML file. So, the permission codes are given below. Copy and paste these codes under the package name.

android:versionCode="1"
android:versionName="1.0"
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

and also you need to add another one code in the Application section 

android:screenOrientation="portrait"

Step 2: MainActivity.XML For Flashlight using Android Studio:

Now, you need to open layout folder and also open main activity.XML file. Delete all existing code and paste following code in the main activity.XML file.

<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:background="#4F0C4E"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <ImageButton
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@null"
        android:contentDescription="@null"
        android:src="@drawable/btn_on" />
</RelativeLayout>

Step 3: MainActivity.java Code For Android Flashlight App :

Now, You need to run the app MainActivity Java code. Therefore, you need to copy and paste following code under your package name in  MainActivity.java file.

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class MainActivity extends Activity {
    InterstitialAd mInterstitialAd;
    private InterstitialAd interstitial;
    private ImageButton btn;

    private Camera mcamera;
    private boolean FlashOn;
    private boolean Flash;
    private Parameters fparams;
    private MediaPlayer mp3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        AdRequest adRequest = new AdRequest.Builder().build();
       

// Prepare the Interstitial Ad
        interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
        interstitial.setAdUnitId("ca-app-pub-1177796718682565/3856232578");

        interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
        interstitial.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // Call displayInterstitial() function
                displayInterstitial();
            }
            public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
                if (interstitial.isLoaded()) {
                    interstitial.show();
                }
            }
        });
        // flash switch button
        btn = (ImageButton) findViewById(R.id.btn);

      /*
       * First check if device is supporting flashlight or not
       */
        Flash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        if (!Flash) {
            // device doesn't support flash
            // Show alert message and close the application
            AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
                    .create();
            alert.setTitle("Error");
            alert.setMessage("Sorry, your device doesn't support flash light!");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // closing the application
                    finish();
                }
            });
            alert.show();
            return;
        }

        // get the camera
        getCamera();

        // displaying button image
        toggleButtonImage();

      /*
       * Switch button click event to toggle flash on/off
       */
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (FlashOn) {
                    // turn off flash
                    turnOffFlash();
                } else {
                    // turn on flash
                    turnOnFlash();
                }
            }
        });
    }

    /*
     * Get the camera
     */
    private void getCamera() {
        if (mcamera == null) {
            try {
                mcamera = Camera.open();
                fparams = mcamera.getParameters();
            } catch (RuntimeException e) {
                Log.e("Camera Error. Failed ", e.getMessage());
            }
        }
    }

    /*
     * Turning On flash
     */
    private void turnOnFlash() {
        if (!FlashOn) {
            if (mcamera == null || fparams == null) {
                return;
            }
            // play sound
            playSound();

            fparams = mcamera.getParameters();
            fparams.setFlashMode(Parameters.FLASH_MODE_TORCH);
            mcamera.setParameters(fparams);
            mcamera.startPreview();
            FlashOn = true;

            // changing button/switch image
            toggleButtonImage();
        }

    }

    /*
     * Turning Off flash
     */
    private void turnOffFlash() {
        if (FlashOn) {
            if (mcamera == null || fparams == null) {
                return;
            }
            // play sound
            playSound();

            fparams = mcamera.getParameters();
            fparams.setFlashMode(Parameters.FLASH_MODE_OFF);
            mcamera.setParameters(fparams);
            mcamera.stopPreview();
            FlashOn = false;

            // changing button/switch image
            toggleButtonImage();
        }
    }

    /*
     * Playing sound will play button toggle sound on flash on / off
     */
    private void playSound() {
        if (FlashOn) {
            mp3 = MediaPlayer.create(MainActivity.this, R.raw.light_off);
        } else {
            mp3 = MediaPlayer.create(MainActivity.this, R.raw.light_on);
        }
        mp3.setOnCompletionListener(new OnCompletionListener() {

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

    /*
     * Toggle switch button images changing image states to on / off
     */
    private void toggleButtonImage() {
        if (FlashOn) {
            btn.setImageResource(R.drawable.btn_on);
        } else {
            btn.setImageResource(R.drawable.btn_off);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();

        // on pause turn off the flash
        turnOffFlash();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // on resume turn on the flash
        if (Flash)
            turnOnFlash();
    }

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

        // on starting the app get the camera params
        getCamera();
    }

    @Override
    protected void onStop() {
        super.onStop();

        // on stop release the camera
        if (mcamera != null) {
            mcamera.release();
            mcamera = null;
        }
    }

}

Step 4: On and Off  Button Images For Android Flashlight App

Please download the following two pictures and put in your res> drawable folder in your android studio.

 

make android flashlight

 

Step 5: Build Gradle  (Module: app) for Android Flashlight:

Finally, you need some changes in Build Gradle file without these changes your android flashlight not work. Therefore, these changes are shown in the given screenshot and highlighted. If you want to add AdMob ads in your android flashlight app Please visit our another post how to add AdMob ads on android app

Dependencies : 

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestCompile 'com.android.support:support-annotations:23.3.0'
    compile 'com.google.android.gms:play-services-ads:8.4.0'
}

build-gradle-for-android-flashlight-app

In Conclusion :  

I hope you will create your own android flashlight app using android studio by following our guideline. So, if you are facing any problem then, please comment on our post. We will try to reply your comment within 2 business days.

x

Check Also

add admob ads in android app

How To Add Admob Ads in Android App – Admob Integration Tutorial

 Add Admob Ads In Android App – Admob Integration : Today, we will learn how to ...