12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package com.develop.common.utils
- import java.util.*
- abstract class TimeDownUtil {
- private var mCountDownInterval: Long = 1000
- private var mTimer: Timer? = null
- private var mTimerTask: TimerTask? = null
- /**
- * 时钟回调的次数
- */
- private var mCount = 0
- /**
- * 倒计时时间,默认间隔单位为秒
- *
- * @param time 毫秒
- */
- constructor(time: Long) {
- initTimer(time)
- }
- private fun initTimer(time: Long) {
- mTimer = Timer()
- mCount = (time / mCountDownInterval).toInt()
- mTimerTask = object : TimerTask() {
- override fun run() {
- if (mCount > 0) {
- mCount--
- onTick(mCountDownInterval * mCount)
- } else {
- onFinish()
- cancel()
- }
- }
- }
- }
- /**
- * 倒计时时间,默认单位为秒
- *
- * @param time
- * @param countDownInterval 间隔时间,1000为1s
- */
- constructor(time: Long, countDownInterval: Long) {
- mCountDownInterval = countDownInterval
- initTimer(time)
- }
- fun start() {
- mTimer?.schedule(mTimerTask, 0, mCountDownInterval)
- }
- /**
- * Callback fired on regular interval.
- *
- * @param millisUntilFinished 距离结束还有多少时间
- */
- abstract fun onTick(millisUntilFinished: Long)
- /**
- * 倒计时结束的回调
- */
- abstract fun onFinish()
- fun cancel() {
- mTimer?.cancel()
- mTimerTask?.cancel()
- }
- }
|