Skip to content

How to Build a Simple Flashlight Android App?

  • by

A simple flashlight or torchlight Android app is a mobile application that utilizes the device’s camera flash (LED) to produce a bright light, simulating the functionality of a traditional flashlight. Users can turn the flashlight on and off with a simple user interface, often through a button or toggle switch within the app.

Build a Simple Flashlight/TorchLight Android App

Building a simple flashlight app for Android is a great beginner’s project. Below are the basic steps to create a flashlight app using Android Studio:

Set Up Your Development Environment

  1. Install Android Studio:
    • Download and install Android Studio from the official website: Android Studio.
  2. Create a New Project:
    • Open Android Studio and start a new project.
    • Choose an empty activity and set a name for your project.

Design the User Interface (UI)

Open activity_main.xml:

  • Design the UI in XML. Place a ToggleButton (for on/off functionality) and set its ID.
  • Open res/layout/activity_main.xml and add the following code for a basic UI with a ToggleButton:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="OFF"
        android:textOn="ON"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Implement Flashlight Functionality

Open MainActivity.kt and add the following code:

package com.example.flashlight

import android.content.Context
import android.content.pm.PackageManager
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.widget.CompoundButton
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi

class MainActivity : ComponentActivity() {
    private lateinit var toggleButton: CompoundButton
    private var isFlashOn: Boolean = false
    private var cameraManager: CameraManager? = null
    private var cameraId: String? = null

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        toggleButton = findViewById(R.id.toggleButton)
        cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager?

        // Check if the device has a flash
        if (!hasFlash()) {
            toggleButton.isEnabled = false
            return
        }

        // Get the camera ID
        cameraId = cameraManager?.cameraIdList?.get(0)

        toggleButton.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                turnOnFlashlight()
            } else {
                turnOffFlashlight()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun hasFlash(): Boolean {
        return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun turnOnFlashlight() {
        try {
            if (cameraId != null) {
                cameraManager?.setTorchMode(cameraId!!, true)
                isFlashOn = true
            }
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun turnOffFlashlight() {
        try {
            if (cameraId != null) {
                cameraManager?.setTorchMode(cameraId!!, false)
                isFlashOn = false
            }
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    override fun onStop() {
        super.onStop()
        if (isFlashOn) {
            turnOffFlashlight()
        }
    }
}

Request Camera Permission

Open AndroidManifest.xml and add the following permission request:

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

Complete code.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Flashlight"
        tools:targetApi="31">

        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.Flashlight">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Run Your App

Connect your device or use an emulator and run the app. You should be able to turn the flashlight on and off using the toggle button.

This is a simple example, and in a production environment, you should handle exceptions, edge cases, and manage the camera resource more carefully. Additionally, consider using the Camera2 API for better compatibility with newer Android versions.

Output:

How to Build a Simple Flashlight Android App?