Created
July 14, 2020 12:28
-
-
Save vaibhavpandeyvpz/ea5089882bb49b78938a5cf0a4209bb8 to your computer and use it in GitHub Desktop.
Countdown timer for Android, support pause & resume functions.
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
import android.os.Handler | |
import java.util.concurrent.TimeUnit | |
class ResumableTimer( | |
private var duration: Long, // in milliseconds | |
private var delay: Long = TimeUnit.SECONDS.toMillis(1), // in milliseconds | |
private val listener: OnCountDownListener? | |
) { | |
interface OnCountDownListener { | |
fun onCountDownFinished() | |
fun onCountDownTick(elapsed: Long, // in milliseconds | |
remaining: Long, // in milliseconds | |
total: Long) // in milliseconds | |
} | |
private var handler = Handler() | |
var remaining = duration | |
private lateinit var runnable: Runnable | |
init { | |
runnable = Runnable { | |
remaining -= delay | |
listener?.onCountDownTick(duration - remaining, remaining, duration) | |
if (remaining > 0) { | |
handler.postDelayed(runnable, delay) | |
} else { | |
stop() | |
listener?.onCountDownFinished() | |
} | |
} | |
} | |
fun start(restart: Boolean = false) { | |
if (restart) { | |
handler.removeCallbacks(runnable) | |
remaining = duration | |
} | |
handler.postDelayed(runnable, delay) | |
} | |
fun stop() { | |
handler.removeCallbacks(runnable) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment