DEV Community

Dhruv Joshi
Dhruv Joshi

Posted on

How to code a simple Flash light Android app? Step by Step Detailed Guide with Code

To create a simple flashlight app for Android, you will need to use the Android SDK and programming language such as Java or Kotlin. Here is a step-by-step guide for creating a basic flashlight app in Android Studio, with code examples:

Install the Android Studio development environment and set up an emulator or connect a physical Android device to your computer.

Create a new Android project in Android Studio.

Design the layout of your app. This will involve creating the necessary XML files to define the user interface of your app, including any buttons or other UI elements you want to include. For this example, we will create a simple layout with a single toggle button to turn the flashlight on and off. Add the following code to your layout XML file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_flashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toggle Flashlight"
        android:onClick="toggleFlashlight" />

</LinearLayout>

Enter fullscreen mode Exit fullscreen mode
  • In your app's main activity, define a method to handle the flashlight toggle button press. This method will use the Android CameraManager class to control the device's camera flash through the use of camera "torch" mode. Add the following code to your activity:
private boolean flashlightOn = false;

public void toggleFlashlight(View view) {
    // Get the camera manager
    CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

    try {
        // Get the camera id for the first camera
        String cameraId = cameraManager.getCameraIdList()[0];

        // Toggle the flashlight on or off
        if (flashlightOn) {
            cameraManager.setTorchMode(cameraId, false);
            flashlightOn = false;
        } else {

Enter fullscreen mode Exit fullscreen mode

Boom! You created a flashlight app! Reach me if you want any help and guidance on your project.

Top comments (0)