In this tutorial, we will look into how to create a flashlight app in android, how it is implemented, how to get the camera permission for flashlight and finally understand how to define a flashlight example .

Today the smartphones are very useful part of our everyday life it can do a lot of different things .In Android lollipop 5.0 google has introduced a very useful feature Flash Light for android smartphones .

Flashlight instantly turns your device into the brightest led flash light & strongest torch light. Flashlight uses your camera flash as a flashlight ,so if your android device has a camera flash then you can use it as a flashlight i.e. if your camera has no flash then you can’t . Here in this example we implement flashlight on and flashlight off button to test flashlight apps .

1. Create a New Project :

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to implement flashlight in android using android studio.

2.  Add Camera Permission to AndroidManifest.xml :

Now open AndroidManifest.xml file and add required permission to access camera

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

3. Create a Button to activity_main.xml  :

Create a button to your main layout i.e. activity_main.xml

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

    <Button
        android:background="@android:color/holo_red_light"
        android:id="@+id/btnFlash"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:text="ON" />


</RelativeLayout>

4. Now open your MainActivity.java and add following code :

Now implement the onClickListener() for flashlight on  and flashlight off button , camera permission and use the camera flash to create a flash light or just implement the following code .

package net.technxt;

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 btnFlashLight;
    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);

        btnFlashLight = findViewById(R.id.btnFlash);

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

            }
        });
    }

    private void flashLight() {
        if (hasCameraFlash) {
            if (isFlashOn) {
                btnFlashLight.setText("ON");
                flashLightOff();
                isFlashOn=false;
            } else {
                btnFlashLight.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;
        }
    }

Now run the project/app to test flashlight apps example through android device or any Emulator .

%d bloggers like this: