How to Switch Torch or Flash Light on and off in Android App Using Android Studio and Java Full Project For Beginners

 

 

package com.example.torchflashlightcontroller;

import androidx.appcompat.app.AppCompatActivity;

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 CameraManager cameraManager;
private String cameraID;

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

cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraID = cameraManager.getCameraIdList()[0]; // 0 is for back camera and 1 is for front camera
} catch (Exception e) {
e.printStackTrace();
}
}

public void TorchONButtonClick(View view){
try {
cameraManager.setTorchMode(cameraID, true);
} catch (Exception e) {
e.printStackTrace();
}
}

public void TorchOFFButtonClick(View view){
try {
cameraManager.setTorchMode(cameraID, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}

 

 

<?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”>

<Button
android:id=”@+id/button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginStart=”154dp”
android:layout_marginTop=”125dp”
android:onClick=”TorchONButtonClick”
android:text=”@string/torch_on”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent” />

<Button
android:id=”@+id/button2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginStart=”155dp”
android:layout_marginTop=”99dp”
android:onClick=”TorchOFFButtonClick”
android:text=”@string/torch_off”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toBottomOf=”@+id/button” />
</androidx.constraintlayout.widget.ConstraintLayout>

Leave a Reply