How To Make Flashlight Application in Android Studio

 Make Flashlight Application In Android :

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

Step 1: Manifest.xml in the android studio for Flashlight Application:

First of all, you need camera permission in the Manifest.xml file to make a 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.

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

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

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/Flash"
        android:layout_width="144dp"
        android:layout_height="83dp"
        android:layout_centerInParent="true"
        android:background="#F0EC1907"
        android:text="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 the following code under your package name in the MainActivity.java file.

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    Button FlashLight;
    private final int CAMERA_REQUEST_CODE=2;
    boolean hasCameraFlash = false;
    private boolean isFlashOn=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hasCameraFlash = getPackageManager().
                hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        FlashLight =  (Button)findViewById(R.id.Flash);

        FlashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                askPermission(Manifest.permission.CAMERA,CAMERA_REQUEST_CODE);

            }
        });
    }

    private void flashLight() {
        if (hasCameraFlash) {
            if (isFlashOn) {
                FlashLight.setText("ON");
                flashLightOff();
                isFlashOn=false;
            } else {
                FlashLight.setText("OFF");
                flashLightOn();
                isFlashOn=true;
            }
        } else {
            Toast.makeText(MainActivity.this, "No flash available on your device",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void flashLightOn() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, true);
        } catch (CameraAccessException e) {
        }
    }

    private void flashLightOff() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            String cameraId = cameraManager.getCameraIdList()[0];
            cameraManager.setTorchMode(cameraId, false);
        } catch (CameraAccessException e) {
        }
    }

    private void askPermission(String permission,int requestCode) {
        if (ContextCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
            // We Dont have permission
            ActivityCompat.requestPermissions(this,new String[]{permission},requestCode);

        }else {
            // We already have permission do what you want
            flashLight();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    hasCameraFlash = getPackageManager().
                            hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
                    Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_LONG).show();
                    flashLight();

                } else {
                    Toast.makeText(this, "Camera Permission Denied", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }}

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

If you want to add buttons instead of text. So, Please download the following two pictures and put them 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 the 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 :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.myapplicationgh"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:24.2.1'
    implementation 'com.android.support:support-v4:24.2.1'
    androidTestImplementation 'junit:junit:4.12'
}

Build.Gradle (Project: MyApplication) and Gradle-Wrapper.properties(Gradle Version)

Build.Gradle (Project: application): You need to change android tools to build the Gradle version in the dependencies classpath.

classpath 'com.android.tools.build:gradle:3.1.0'

Gradle-Wrapper.properties(Gradle Version): We also need to change the Gradle version to run the MainActivity.java Code. So, Please change your Gradle version with the following codes. Finally, Once You’re all Gradle setting will be changed then press on the Sync Now button. Now, Android studio will start to download whole the dependencies.

distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
Make Flashlight Application In Android Studio

In Conclusion :  

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