Open In App

How to Build a Simple Torch App in Android using Kotlin?

Improve
Improve
Like Article
Like
Save
Share
Report

Torch Application is a very basic application that every beginner level android developer should definitely try to build while learning Android. In this article, we will be creating an application in which we will simply display a toggle button to switch on and switch off the torch. 

Note: If you are looking to implement the Torch application in android using Java. Check out the following article: Torch Application in Android using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

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

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a simple text view
        for displaying the current status of the torch-->
    <TextView
        android:id="@+id/idTVTorchStatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="200dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Torch Off"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="25sp"
        android:textStyle="bold" />
 
    <!--on below line we are simply displaying a
         toggle button for making torch on and off-->
    <ToggleButton
        android:id="@+id/idBtnSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVTorchStatus"
        android:layout_margin="20dp"
        android:backgroundTint="@color/purple_200"
        android:padding="5dp"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textStyle="bold" />
 
</RelativeLayout>


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import android.widget.ToggleButton
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating variable
    // for toggle button, text view for torch status.
    lateinit var toggleBtn: ToggleButton
    lateinit var torchStatusTV: TextView
 
    // on below line we are creating
    // a variable for camera manager.
    lateinit var cameraManager: CameraManager
 
    // one below line we are
    // creating a string for camera ID
    lateinit var cameraID: String
 
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing our
        // toggle button and torch status text view.
        toggleBtn = findViewById(R.id.idBtnSwitch)
        torchStatusTV = findViewById(R.id.idTVTorchStatus)
         
        // on below line we are initializing our camera manager.
        cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            // O means back camera unit,
            // 1 means front camera unit
            // on below line we are getting camera id
            // for back camera as we will be using
            // torch for back camera
            cameraID = cameraManager.cameraIdList[0]
        } catch (e: Exception) {
            // on below line we are handling exception.
            e.printStackTrace()
        }
 
        // on below line we are adding on
        // click listener for toggle button.
        toggleBtn.setOnClickListener {
            // on below line we are checking
            // if the toggle button is checked.
            if (toggleBtn.isChecked) {
                try {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                         // if button is checked we are simply
                         // initializing our camera manager and
                         // setting torch mode for back camera
                         // as true to switch on torch
                        cameraManager.setTorchMode(cameraID, true)
                         
                        // on the below line we are simply displaying
                        // a toast message for torch on.
                        Toast.makeText(this@MainActivity, "Torch turned on..", Toast.LENGTH_LONG)
                            .show()
                         
                        // on below line we are setting text
                        // to our text view as torch on.
                        torchStatusTV.setText("Torch On")
                    }
                } catch (e: Exception) {
                    // on below line we are handling exception.
                    e.printStackTrace()
                }
            } else {
                // this condition will be called
                // when toggle button is off.
                try {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                        // if button is unchecked this method will be called.
                        // In this method we will initializing our camera
                        // manager with camera id and setting torch to off.
                        cameraManager.setTorchMode(cameraID, false)
                         
                        // on below line we are simply displaying a toast message.
                        Toast.makeText(this@MainActivity, "Torch turned off..", Toast.LENGTH_SHORT)
                            .show()
                         
                        // on below line we are setting text to text view.
                        torchStatusTV.setText("Torch Off")
                    }
                  // on below line we are handling exception
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
 
    // on below line we are switching the torch off
    // when the application is killed in between.
    override fun finish() {
        super.finish()
        // this method will be called
        // when the application closes.
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                // in this method we will be setting camera manager
                // torch mode to false to switch off the camera.
                cameraManager.setTorchMode(cameraID, false)
            }
            // on below line we are displaying a toast message as torch off.
            Toast.makeText(this@MainActivity, "Torch turned off..", Toast.LENGTH_SHORT)
                .show()
          // on below line we are handling exception.
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}


Now run your application to see the output of it. 

Output:



Last Updated : 02 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads