How to Implement Countdown Timers in Kotlin

//this discussion is about implementing countdown timers in an Android App Kotlin.


/*first we need to Intialise Built-in method named CountDownTimer and the textView where we needs to initiliase or setup the timer.*/

lateinit var progress:ProgressDialog

lateinit var countdownTimer: CountDownTimer

lateinit var timerTextView: TextView


override fun onCreate(savedInstanceState: Bundle?) {

progress = ProgressDialog(this,4)

progress.setTitle("Nescafe")

progress.setMessage("Loading, Please wait.")

progress.setCancelable(false)

progress.setCanceledOnTouchOutside(true)



sharedPreferences = SharedPreference(this)

super.onCreate(savedInstanceState)

timerTextView = findViewById(R.id.timerTextView)


//we can use it with LifecycleScope

lifecycleScope.launch {

val delayTimeMillis = 22000L //initialise the Seconds in Milliseconds for Timer to start

val updateIntervalMillis = 1000L // Update the timer (for every second or every two seconds )


countdownTimer = object : CountDownTimer(delayTimeMillis, updateIntervalMillis) {

override fun onTick(millisUntilFinished: Long) {

val secondsRemaining = millisUntilFinished / 1000

timerTextView.text = "Time Left : ${secondsRemaining}s"

if(secondsRemaining<=2){

// you can intilise a toast or print a message or set a message like an alert if the time left is this particular seconds

// here i'm using a toast

Toast.makeText(this@FeedbackActivity,"hurry Up!",Toast.LENGTH_LONG).show()


}

}



/*we can initialise anything after timer getting finihsed (like returning to main activity or going to another screen or exiting the app)*/

override fun onFinish() {

timerTextView.text = "Time Left : 0s"

intent = Intent(this@FeedbackActivity, startingActivity::class.java)

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)

startActivity(intent)

sharedPreferences.clearSharedPreference()

}

}


countdownTimer.start()

}

}


//initialise what to do if the Activity in Pause State

override fun onPause() {

super.onPause()

if(progress.isShowing){

progress.dismiss()

}

countdownTimer.cancel()

}

//initialise what to do if the Activity in Resume State

override fun onResume() {

super.onResume()

countdownTimer.start()

}

//initialise what to do if the Activity in Destroy State

override fun onDestroy() {

super.onDestroy()

if(progress.isShowing){

progress.dismiss()

}

countdownTimer.cancel()

}

Tagged:
Sign In or Register to comment.