COME 2 CODE
Learn by Yourself

How to make a Torch using JAVA in Android Studio

Hello friends,we are now going to make a project in which we can turn on and off out Flashlight using JAVA. Make a new project and go to MainActivity.java and type the following code in it.

MainActivity.java :

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
  private SwitchCompat lightOnOff;
  private CameraManager cameraManager;
  private String getCameraID;

  @SuppressLint("MissingInflatedId")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lightOnOff = findViewById(R.id.toggle_flashlight);
    cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
      getCameraID = cameraManager.getCameraIdList()[0];
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  }

  public void toggleFlashLight(View view) {
    if (lightOnOff.isChecked()) {
    try {
      cameraManager.setTorchMode(getCameraID, true);
    } catch (CameraAccessException e) {
      e.printStackTrace();
    }
  } else {
    try {
      cameraManager.setTorchMode(getCameraID, false);
    } catch (CameraAccessException e) {
      e.printStackTrace();
      }
    }
  }
}

Now, go to activity_main.xml and type the following code in it.

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity"
  android:background="@color/background">

  <androidx.appcompat.widget.SwitchCompat
    android:id="@+id/toggle_flashlight"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="toggleFlashLight"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
QUICK LINKS :