androidkotlinflashlight

Flashlight for Android on Kotlin


You need to turn on the LED on your phone. I wrote a simple application. The LED should turn on when the app starts. The code matches the solutions on Stackoverflow Application code:

package com.example.flash

import android.hardware.Camera
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

 override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)
     var cam = Camera.open()
     var p = cam.parameters
     p.flashMode = Camera.Parameters.FLASH_MODE_TORCH
     cam.parameters = p
     cam.startPreview()
 }
} 

AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kgskassa">
       <uses-permission android:name="android.permission.INTERNET" />
       <uses-permission android:name="android.permission.CAMERA" />
       <uses-permission android:name="android.permission.FLASHLIGHT"/>
       <uses-feature android:name="android.hardware.camera" />
       <uses-feature android:name="android.hardware.camera.autofocus"/>

Access to the camera on the phone is allowed. Does not work. Ideas?


Solution

  • package com.example.flash
    
    import android.content.Context
    import android.hardware.camera2.CameraAccessException
    import android.hardware.camera2.CameraManager
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    
    class MainActivity : AppCompatActivity() {
        var flashLightStatus: Boolean = false
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            openFlashLight()
        }
    
        private fun openFlashLight() {
            val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
            val cameraId = cameraManager.cameraIdList[0]
            if (!flashLightStatus) {
                try {
                    cameraManager.setTorchMode(cameraId, true)
                    flashLightStatus = true
    
                } catch (e: CameraAccessException) {
                }
            } else {
                try {
                    cameraManager.setTorchMode(cameraId, false)
                    flashLightStatus = false
                } catch (e: CameraAccessException) {
                }
            }
    
        }
    }