Make a Flashlight Apps in Android Studio - FULL PROJECT Detailed Tutorial!
Here's a step-by-step tutorial on how to make a flashlight app in Android Studio:
Create a new Android Studio project with an Empty Activity.
Open the app's build.gradle file and add the following line to the dependencies block:
pythonimplementation 'androidx.camera:camera-core:1.1.0-alpha04'
This line adds the CameraX library to the project, which we will use to access the device's flashlight.
Open the app's main layout file (activity_main.xml) and add a Button and a TextView. Set the Button's text to "ON" and the TextView's text to "Flashlight Off".
In the MainActivity class, create a private variable to hold the Camera object:
javaprivate var camera: Camera? = null
- In the onCreate() method, set the Button's onClickListener:
scssfindViewById<Button>(R.id.button).setOnClickListener {
toggleFlashlight()
}
- Create a private toggleFlashlight() method that will turn the flashlight on or off:
kotlinprivate fun toggleFlashlight() {
if (camera == null) {
try {
camera = Camera.open()
val parameters = camera?.parameters
parameters?.flashMode = Camera.Parameters.FLASH_MODE_TORCH
camera?.parameters = parameters
camera?.startPreview()
findViewById<TextView>(R.id.textView).text = "Flashlight On"
findViewById<Button>(R.id.button).text = "OFF"
} catch (e: Exception) {
e.printStackTrace()
}
} else {
camera?.stopPreview()
camera?.release()
camera = null
findViewById<TextView>(R.id.textView).text = "Flashlight Off"
findViewById<Button>(R.id.button).text = "ON"
}
}
This method first checks if the camera object is null. If it is, it opens the camera, sets the flash mode to torch, starts the preview, and updates the TextView and Button text to indicate that the flashlight is on.
If the camera object is not null, the method stops the preview, releases the camera, sets the camera object to null, and updates the TextView and Button text to indicate that the flashlight is off.
- In the onDestroy() method, release the camera object:
kotlinoverride fun onDestroy() {
super.onDestroy()
camera?.release()
}
This ensures that the camera is released when the app is closed.
That's it! You have successfully created a flashlight app in Android Studio using the CameraX library.
No comments