TimeDownUtil.kt 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.develop.common.utils
  2. import java.util.*
  3. abstract class TimeDownUtil {
  4. private var mCountDownInterval: Long = 1000
  5. private var mTimer: Timer? = null
  6. private var mTimerTask: TimerTask? = null
  7. /**
  8. * 时钟回调的次数
  9. */
  10. private var mCount = 0
  11. /**
  12. * 倒计时时间,默认间隔单位为秒
  13. *
  14. * @param time 毫秒
  15. */
  16. constructor(time: Long) {
  17. initTimer(time)
  18. }
  19. private fun initTimer(time: Long) {
  20. mTimer = Timer()
  21. mCount = (time / mCountDownInterval).toInt()
  22. mTimerTask = object : TimerTask() {
  23. override fun run() {
  24. if (mCount > 0) {
  25. mCount--
  26. onTick(mCountDownInterval * mCount)
  27. } else {
  28. onFinish()
  29. cancel()
  30. }
  31. }
  32. }
  33. }
  34. /**
  35. * 倒计时时间,默认单位为秒
  36. *
  37. * @param time
  38. * @param countDownInterval 间隔时间,1000为1s
  39. */
  40. constructor(time: Long, countDownInterval: Long) {
  41. mCountDownInterval = countDownInterval
  42. initTimer(time)
  43. }
  44. fun start() {
  45. mTimer?.schedule(mTimerTask, 0, mCountDownInterval)
  46. }
  47. /**
  48. * Callback fired on regular interval.
  49. *
  50. * @param millisUntilFinished 距离结束还有多少时间
  51. */
  52. abstract fun onTick(millisUntilFinished: Long)
  53. /**
  54. * 倒计时结束的回调
  55. */
  56. abstract fun onFinish()
  57. fun cancel() {
  58. mTimer?.cancel()
  59. mTimerTask?.cancel()
  60. }
  61. }