-6

im new at coding, i dont know even basics but

I need make somekind 20 seconds countdown timer and i didin't found any working tutorials.

I tried my best but always some error came up.

  • 1
    you can use `CountDownTimer` in Android – Alan Deep May 09 '20 at 21:31
  • 3
    Does this answer your question? [How to make a countdown timer in Android?](https://stackoverflow.com/questions/10032003/how-to-make-a-countdown-timer-in-android) – Pedro Coelho May 09 '20 at 21:47
  • You can just use coroutines and delay for 20_000 milliseconds, till then coroutine will be suspended meaning it will be detached from thread. It is less expensive resource than a standalone thread. – Animesh Sahu May 10 '20 at 02:48

1 Answers1

1

pass time in milliseconds.
var countDownTimer: CountDownTimer? = null //declare it as global variable

fun startCountDown(time: Long) {
        countDownTimer = object: CountDownTimer(time,1000){
          override fun onFinish() {
            Timber.v("Countdown: Finished")
            visibility = View.GONE
          }

          override fun onTick(millisUntilFinished: Long) {
            Timber.v("Countdown: $millisUntilFinished")
            visibility = View.VISIBLE
            updateTimeView(millisUntilFinished)
          }

        }
        countDownTimer?.start()
      }

For example:

startCountDown(30000), will countdown from 30 to 0.

Note: Don't forget to stop the timer when your app stops:

override fun onStop() {
    super.onStop()
    countDownTimer?.cancel()
  }
Alan Deep
  • 2,037
  • 1
  • 14
  • 22