Open In App

How to Build a Simple Flashlight/TorchLight Android App?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

All the beginners who are into the android development world should build a simple android application that can turn on/off the flashlight or torchlight by clicking a Button. So at the end of this article, one will be able to build their own android flashlight application with a simple layout. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 




Steps for Building a Simple Flashlight/TorchLight Android App

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:text="Flashlight"
        android:textColor="@color/colorPrimary"
        android:textSize="50sp"
        android:textStyle="bold|italic" />

    <!-- This is the simple divider between above TextView and ToggleButton -->
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="32dp"
        android:background="@android:color/darker_gray" />

    <!-- This toggle button by default toggles between the ON and OFF we no need to set separate TextView for it -->
    <ToggleButton
        android:id="@+id/toggle_flashlight"
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:layout_gravity="center"
        android:layout_marginTop="32dp"
        android:onClick="toggleFlashLight"
        android:textSize="25sp" />

</LinearLayout>

The following output UI is produced:


Step 3: Handling the Toggle Button widget to toggle ON or OFF inside the MainActivity.java file

The complete code for the MainActivity.java file is given below. Comments are added inside the code to understand the code in more detail. 

Java
package com.yourpackage;

import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private ToggleButton toggleFlashLightOnOff;
    private CameraManager cameraManager;
    private String getCameraID;

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

        // Register the ToggleButton with specific ID
        toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight);

        // CameraManager to interact with camera devices
        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        // Exception is handled to check whether the camera resource is being used by another service or not
        try {
            // 0 means back camera unit, 1 means front camera unit
            getCameraID = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    // RequiresApi is set because devices below API level 23 (Marshmallow) don't have the flash unit with the camera
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void toggleFlashLight(View view) {
        if (toggleFlashLightOnOff.isChecked()) {
            // Exception is handled to check whether the camera resource is being used by another service or not
            try {
                // true sets the torch in ON mode
                cameraManager.setTorchMode(getCameraID, true);

                // Inform the user about the flashlight status using Toast message
                Toast.makeText(MainActivity.this, "Flashlight is turned ON", Toast.LENGTH_SHORT).show();
            } catch (CameraAccessException e) {
                // Prints stack trace on standard error output error stream
                e.printStackTrace();
            }
        } else {
            // Exception is handled to check whether the camera resource is being used by another service or not
            try {
                // false sets the torch in OFF mode
                cameraManager.setTorchMode(getCameraID, false);

                // Inform the user about the flashlight status using Toast message
                Toast.makeText(MainActivity.this, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show();
            } catch (CameraAccessException e) {
                // Prints stack trace on standard error output error stream
                e.printStackTrace();
            }
        }
    }

    // When you click on the button and the torch opens and you do not close the torch again, this code will turn off the torch automatically
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void finish() {
        super.finish();
        try {
            // false sets the torch in OFF mode
            cameraManager.setTorchMode(getCameraID, false);

            // Inform the user about the flashlight status using Toast message
            Toast.makeText(MainActivity.this, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show();
        } catch (CameraAccessException e) {
            // Prints stack trace on standard error output error stream
            e.printStackTrace();
        }
    }
}
Kotlin
package com.yourpackage

import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import android.widget.ToggleButton
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private var toggleFlashLightOnOff: ToggleButton? = null
    private var cameraManager: CameraManager? = null
    private var getCameraID: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Register the ToggleButton with specific ID
        toggleFlashLightOnOff = findViewById(R.id.toggle_flashlight)

        // CameraManager to interact with camera devices
        cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager

        // Exception is handled to check whether the camera resource is being used by another service or not
        try {
            // 0 means back camera unit, 1 means front camera unit
            getCameraID = cameraManager!!.cameraIdList[0]
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    // RequiresApi is set because devices below API level 23 don't have the flash unit with the camera
    @RequiresApi(Build.VERSION_CODES.M)
    fun toggleFlashLight(view: View?) {
        if (toggleFlashLightOnOff!!.isChecked) {
            // Exception is handled to check whether the camera resource is being used by another service or not
            try {
                // true sets the torch in ON mode
                cameraManager!!.setTorchMode(getCameraID!!, true)

                // Inform the user about the flashlight status using Toast message
                Toast.makeText(this@MainActivity, "Flashlight is turned ON", Toast.LENGTH_SHORT).show()
            } catch (e: CameraAccessException) {
                // Prints stack trace on standard error output error stream
                e.printStackTrace()
            }
        } else {
            // Exception is handled to check whether the camera resource is being used by another service or not
            try {
                // false sets the torch in OFF mode
                cameraManager!!.setTorchMode(getCameraID!!, false)

                // Inform the user about the flashlight status using Toast message
                Toast.makeText(this@MainActivity, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show()
            } catch (e: CameraAccessException) {
                // Prints stack trace on standard error output error stream
                e.printStackTrace()
            }
        }
    }

    // When you click on the button and the torch opens and you do not close the torch again, this code will turn off the torch automatically
    @RequiresApi(Build.VERSION_CODES.M)
    override fun finish() {
        super.finish()
        try {
            // false sets the torch in OFF mode
            cameraManager!!.setTorchMode(getCameraID!!, false)

            // Inform the user about the flashlight status using Toast message
            Toast.makeText(this@MainActivity, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show()
        } catch (e: CameraAccessException) {
            // Prints stack trace on standard error output error stream
            e.printStackTrace()
        }
    }
}
  • Read about the printStackTrace() function here: Throwable printStackTrace() method in Java with Examples.
  • After handling the ToggleButton one needs to test the application under a physical android device. Because if you run the application in the emulator which comes with android studio, the app is going to crash as soon as ToggleButton is clicked, because the emulator device wouldn’t come with the camera flash unit.
  • This method of accessing the camera hardware doesn’t require special permission from the user to access the camera unit. Because in this we are accessing the flash unit through only camera ID (whether it’s a front camera or back camera).

Output:




Next Article
Article Tags :
Practice Tags :

Similar Reads