Android FlashLight Tutorial

Filed Under: Android

In this tutorial, we’ll be implementing the FlashLight feature in our application.

Android FlashLight

Every smartphone nowadays has the flashlight feature/torch available through the camera flash.

In the next part, we’ll be using the Camera2 API to toggle the flashlight. The Camera API was deprecated since Android API 25. Also, we’ll see how to create a blinking flashlight.

Let’s get started by creating a new Android Studio project.

Android Studio Flash Light Project Structure

android flashlight project structure

Code

The code for the activity_main.xml layout file is given below:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnFlashLightToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="FLASHLIGHT OFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnBlinkFlashLight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="BLINK FLASHLIGHT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnFlashLightToggle" />


</android.support.constraint.ConstraintLayout>

Add the following to your AndroidManifest.xml file inside the manifest tag.


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

The code for the MainActivity.java class is given below:


package com.journaldev.androidflashlight;

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.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, btnBlinkFlashLight;
    private static final int CAMERA_REQUEST = 123;
    boolean hasCameraFlash = false;

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


        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);

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

        btnFlashLight = findViewById(R.id.btnFlashLightToggle);
        btnBlinkFlashLight = findViewById(R.id.btnBlinkFlashLight);

        btnFlashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (hasCameraFlash) {
                    if (btnFlashLight.getText().toString().contains("ON")) {
                        btnFlashLight.setText("FLASHLIGHT OFF");
                        btnBlinkFlashLight.setText("BLINK FLASHLIGHT OFF");
                        flashLightOff();
                    } else {
                        btnBlinkFlashLight.setText("BLINK FLASHLIGHT ON");
                        btnFlashLight.setText("FLASHLIGHT ON");
                        flashLightOn();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "No flash available on your device",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnBlinkFlashLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(btnFlashLight.getText().toString().contains("ON"))
                {
                    blinkFlash();
                }
                else{
                    Toast.makeText(MainActivity.this, "Press the above button first.",
                            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 blinkFlash()
    {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        String myString = "0101010101";
        long blinkDelay = 50; //Delay in ms
        for (int i = 0; i < myString.length(); i++) {
            if (myString.charAt(i) == '0') {
                try {
                    String cameraId = cameraManager.getCameraIdList()[0];
                    cameraManager.setTorchMode(cameraId, true);
                } catch (CameraAccessException e) {
                }
            } else {
                try {
                    String cameraId = cameraManager.getCameraIdList()[0];
                    cameraManager.setTorchMode(cameraId, false);
                } catch (CameraAccessException e) {
                }
            }
            try {
                Thread.sleep(blinkDelay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    hasCameraFlash = getPackageManager().
                            hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
                } else {
                    btnFlashLight.setEnabled(false);
                    btnBlinkFlashLight.setEnabled(false);
                    Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

In the above code, we first ask for the camera permissions.

Once that’s done, we check if the Camera flash feature is present or not.

btnFlashLight is used as a flashlight toggle button.

We start the flashlight by getting the first element from the camera id list over the CameraManager.

Over that id, we can set the torch mode to true to enable the flashlight or to false to disable it.

How to make the flashlight blink?

We use a string which consists of a binary number. We iterate through the string and toggle the flashlight on each iteration while making the thread sleep for a moment to bring that blinking effect.

In order to make it blink endlessly use an infinite loop which stops on a condition.

The output of the above application is the desired one. We’ve omitted the screenshot since it is something that’s on the hardware.

This brings an end to this tutorial on FlashLight. You can download the project from the link below:

Comments

  1. Ibrahin Cruz says:

    Hi, thanks for you code, is excellent. I have a question, The for sentence makes freeze the app, how I can do to make a infinite blink app with a stop button?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages