Skip to content

Instantly share code, notes, and snippets.

@nikartx
Last active April 23, 2020 23:48
Show Gist options
  • Save nikartx/0b7e792f6610b7df1456a15515f4ba59 to your computer and use it in GitHub Desktop.
Save nikartx/0b7e792f6610b7df1456a15515f4ba59 to your computer and use it in GitHub Desktop.
Countdown timer
import android.os.CountDownTimer
import java.util.concurrent.TimeUnit
/**
* Countdown timer helper
* @author Ivan V on 23.04.2020.
* @version 1.0
*/
class SimpleTimer {
private var inFuture: Long = 0
private var interval: Long = 0
private lateinit var observer: TimerObserver
private var finished: Boolean = true
private var currentMillis: Long = 0
private lateinit var timer: CountDownTimer
private constructor()
constructor(millisInFuture: Long, countDownInterval: Long, observer: TimerObserver) {
this.inFuture = millisInFuture
this.interval = countDownInterval
this.observer = observer
initTimer()
}
private fun initTimer() {
timer = object: CountDownTimer(inFuture, interval) {
override fun onTick(millisUntilFinished: Long) {
currentMillis = millisUntilFinished
finished = false
timeResolver(millisUntilFinished)
}
override fun onFinish() {
finished = true
observer.timerFinished()
}
}
}
fun start() {
timer.start()
}
fun stop() {
timer.cancel()
finished = true
observer.timerCanceled()
}
fun isFinished() = finished
fun getCurrentMillis() = currentMillis
private fun timeResolver(millisUntilFinished:Long) {
var millis:Long = millisUntilFinished
val days = TimeUnit.MILLISECONDS.toDays(millis)
millis -= TimeUnit.DAYS.toMillis(days)
val hours = TimeUnit.MILLISECONDS.toHours(millis)
millis -= TimeUnit.HOURS.toMillis(hours)
val minutes = TimeUnit.MILLISECONDS.toMinutes(millis)
millis -= TimeUnit.MINUTES.toMillis(minutes)
val seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
observer.timerResult(days, hours, minutes, seconds)
}
/**
* Timer result observer
*/
interface TimerObserver {
fun timerResult(days: Long, hours: Long, minutes: Long, seconds: Long)
fun timerFinished()
fun timerCanceled()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment