Last active
January 27, 2018 14:16
-
-
Save tomaszrykala/c0161b66825f39d7aa055d4b01087734 to your computer and use it in GitHub Desktop.
Timer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const val MSG = 1 | |
class Timer(private val listener: Timer.Listener) { | |
interface Listener { | |
fun onTick(tick: Double) | |
fun onStart() | |
fun onStop() | |
} | |
private val handler = CountUpHandler(this) | |
fun start() { | |
reset() | |
listener.onStart() | |
handler.sendMessage(handler.obtainMessage(MSG)) | |
} | |
fun stop() { | |
listener.onStop() | |
handler.removeMessages(MSG) | |
} | |
private fun onTick(elapsedTime: Double) { | |
listener.onTick(elapsedTime) | |
} | |
private fun reset() { | |
handler.reset() | |
} | |
class CountUpHandler(private val timer: Timer) : Handler() { | |
private var base: Int = 0 | |
override fun handleMessage(msg: Message) { | |
synchronized(this) { | |
base++ | |
timer.onTick(base / 10.0) | |
sendMessageDelayed(obtainMessage(MSG), 100) | |
} | |
} | |
fun reset() { | |
synchronized(this) { | |
base = 0 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment