android kotlin set timerout
import android.os.Handler
import android.os.Looper
class TimerUtil(private val timeoutInMillis: Long, private val onTimeout: () -> Unit) {
private val handler = Handler(Looper.getMainLooper())
private var timerRunnable: Runnable? = null
fun startTimer() {
timerRunnable = Runnable {
onTimeout.invoke()
}
handler.postDelayed(timerRunnable!!, timeoutInMillis)
}
fun stopTimer() {
timerRunnable?.let {
handler.removeCallbacks(it)
}
}
}
Usage:
// Set timeout duration in milliseconds
val timeoutDuration = 5000L
// Create TimerUtil instance with timeout duration and callback function
val timerUtil = TimerUtil(timeoutDuration) {
// Code to execute on timeout
// For example, show a timeout message or perform a specific action
println("Timeout reached!")
}
// Start the timer
timerUtil.startTimer()
// Stop the timer (optional, if needed before timeout)
// timerUtil.stopTimer()