How to Build a Simple Flashlight/TorchLight Android App?

12 Jan, 2022
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. 
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
This layout contains a simple TextView, View (as divider), and one ToggleButton to toggle the Flashlight unit.
Please refer to How to add Toggle Button in an Android Application, to implement, and to see how the toggle button works.
Invoke the following code in the activity_main.xml file or one can design custom widgets.
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
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, because to check whether        // the camera resource is being used by another        // service or not.        try {            // O means back camera unit,            // 1 means front camera unit            getCameraID = cameraManager.getCameraIdList()[0];        } catch (CameraAccessException e) {            e.printStackTrace();        }    }     // RequiresApi is set because, the devices which are    // below API level 10 don't have the flash unit with    // camera.    @RequiresApi(api = Build.VERSION_CODES.M)    public void toggleFlashLight(View view) {        if (toggleFlashLightOnOff.isChecked()) {            // Exception is handled, because 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, because to check            // whether the camera resource is being used by            // another service or not.            try {                // true 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 button and torch open and  // you do not close the tourch again this code  // will off the tourch automatically  @RequiresApi(api = Build.VERSION_CODES.M)    @Override    public void finish() {        super.finish();        try {            // true sets the torch in OFF mode            cameraManager.setTorchMode(getCameraID, false);             // Inform the user about the flashlight            // status using Toast message            Toast.makeText(SlaphScreen.this, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show();        } catch (CameraAccessException e) {            // 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:
himanshugupta3385
simmytarika5
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.