package com.example.flashlight
import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
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()
while (true) {
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
openFlashLight()
}, 5000)
}
}
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) {
}
}
}
private fun closeFlashLight()
{
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraId = cameraManager.cameraIdList[0]
if (flashLightStatus) {
try {
cameraManager.setTorchMode(cameraId, false)
flashLightStatus = false
} catch (e: CameraAccessException) {
}
} else {
try {
cameraManager.setTorchMode(cameraId, true)
flashLightStatus = true
} catch (e: CameraAccessException) {
}
}
}
}
this now just open the flashlight on the phone and the flashlight stay open all the time because the while(true)
while (true) {
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
openFlashLight()
}, 5000)
}
but if I’m removing the while true and doing only:
openFlashLight()
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
closeFlashLight()
}, 5000)
this will open the flashlight and will wait 5 seconds then will close the flashlight.
but I want to make something endless that it will open the flash light wait 5 seconds close the flashlight wait 5 seconds open the flashlight wait 5 seconds close.
that way nonstop. open/close each 5 seconds nonstop. that’s why I tried to use the while(true) but then the flashlight just keep staying open nonstop.
2
Answers
If you want to repeat the flashlight on/off cycles every 5 seconds you can do something like this:
You can achieve this by using kotlin coroutines
and also add this dependency in the build.gradle module level file
And if you want to do it using handler you can try this I am not sure if this will work or not.