Open In App

How to Build a Simple Flashlight/TorchLight Android App?

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 version="1.0" encoding="utf-8"?>
<LinearLayout
    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. 




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 torch again this code
  // will off the torch 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();
        }
    }
}




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 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<Any>(Context.CAMERA_SERVICE) as CameraManager
 
        // 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!!.cameraIdList[0]
        } catch (e: CameraAccessException) {
            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)
    fun 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(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, 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(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 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 fun 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(this@SlaphScreen, "Flashlight is turned OFF", Toast.LENGTH_SHORT).show()
        } catch (e: CameraAccessException) {
            // prints stack trace on standard error
            // output error stream
            e.printStackTrace()
        }
    }
}
    // This code is added by Ujjwal Kumar Bhardwaj

Output:


Article Tags :