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
- 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.
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 MainActivity.java file is given below. Comments are added inside the code to understand the code in more detail.
- Read about the printStackTrace() function here: Throwable printStackTrace() method in Java with Examples.
- After handling the ToggleButton one needs to test the application under 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 it 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 front camera or back camera).
The application UI is produced as:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.