Header Ads

Header ADS

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:

  1. Create a new Android Studio project with an Empty Activity.

  2. Open the app's build.gradle file and add the following line to the dependencies block:

python
implementation '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.

  1. 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".

  2. In the MainActivity class, create a private variable to hold the Camera object:

java
private var camera: Camera? = null
  1. In the onCreate() method, set the Button's onClickListener:
scss
findViewById<Button>(R.id.button).setOnClickListener { toggleFlashlight() }
  1. Create a private toggleFlashlight() method that will turn the flashlight on or off:
kotlin
private 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.

  1. In the onDestroy() method, release the camera object:
kotlin
override 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

Theme images by fpm. Powered by Blogger.