Sure! Here's an example of an Android app written in Kotlin that can turn on the flashlight:
First, add the necessary permissions to the AndroidManifest.xml file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Next, create a new Kotlin class file, e.g., FlashlightActivity.kt, and add the following code:
import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class FlashlightActivity : AppCompatActivity() {
private var isFlashlightOn: Boolean = false
private lateinit var cameraManager: CameraManager
private lateinit var cameraId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_flashlight)
cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
cameraId = cameraManager.cameraIdList[0]
val flashlightButton: Button = findViewById(R.id.flashlightButton)
flashlightButton.setOnClickListener {
toggleFlashlight()
}
}
private fun toggleFlashlight() {
try {
if (isFlashlightOn) {
turnOffFlashlight()
} else {
turnOnFlashlight()
}
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
private fun turnOnFlashlight() {
try {
cameraManager.setTorchMode(cameraId, true)
isFlashlightOn = true
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
private fun turnOffFlashlight() {
try {
cameraManager.setTorchMode(cameraId, false)
isFlashlightOn = false
} catch (e: CameraAccessException) {
e.printStackTrace()
}
}
}
Finally, create the corresponding layout file activity_flashlight.xml and add a button with the ID flashlightButton:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".FlashlightActivity">
<Button
android:id="@+id/flashlightButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Flashlight" />
</LinearLayout>
That's it! When the button is clicked, it will toggle the flashlight on/off.