at this part lines 49-51
override fun onBackPressed() {
}
I tried to look in google but there are so many answers and so different.
now when I'm running the application from the phone I need then to make a long press on the application icon on the phone then info>force stop the back button does nothing the application is keep running. and I want when pressing once the back button that it will close and exit the application.
full code
package com.example.flashlight
import android.content.Context
import android.content.Intent
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.SeekBar
import android.widget.TextView
import kotlin.math.log
class MainActivity : AppCompatActivity() {
var flashLightStatus: Boolean = false
var flashLightOn = false
var counter: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textView)
val seek = findViewById<SeekBar>(R.id.seekBar)
seek.setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
progress: Int,
fromUser: Boolean
) {
// Log.d("seekbar", "Your Progress: ${seekBar?.progress}"
counter = progress.toLong()
textView.text = counter.toString()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) = Unit
override fun onStopTrackingTouch(seekBar: SeekBar?) = Unit
},
)
startFlashLight()
}
override fun onBackPressed() {
}
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) {
}
}
}
fun startFlashLight() {
openFlashLight()
flashLightOn = true
val handler = Handler(Looper.getMainLooper())
handler.postDelayed(object: Runnable {
override fun run() {
if (flashLightOn) {
closeFlashLight()
} else {
openFlashLight()
}
// Changing the toggle and calling the same Runnable again after 5 seconds
flashLightOn = !flashLightOn
handler.postDelayed(this, counter)
}
}, counter)
}
}