Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

CountDownTimer in Android with Example

CountDownTimer is a useful utility class in Android that allows you to schedule a countdown until a time in the future, with regular notifications on intervals along the way. This can be used for various purposes like showing a timer on the screen, scheduling an event to happen after a delay, or building a game mechanism, etc.

Basic Usage:

To use the CountDownTimer, you need to:

  • Define the total time for the countdown and the interval at which you want to receive callbacks.
  • Override the onTick() method, which will be executed at every interval you've defined.
  • Override the onFinish() method, which will be executed when the countdown is done.

Example:

Imagine you're building a simple countdown of 10 seconds that updates a TextView every second and displays a toast message when the countdown finishes.

  • XML Layout (activity_main.xml):
<TextView
    android:id="@+id/timerTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Starting..."
    android:textSize="24sp"/>
  • Kotlin Activity:
class MainActivity : AppCompatActivity() {

    private lateinit var timerTextView: TextView
    private lateinit var countDownTimer: CountDownTimer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        timerTextView = findViewById(R.id.timerTextView)

        countDownTimer = object : CountDownTimer(10000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val secondsRemaining = millisUntilFinished / 1000
                timerTextView.text = "$secondsRemaining seconds remaining"
            }

            override fun onFinish() {
                timerTextView.text = "Done!"
                Toast.makeText(this@MainActivity, "Countdown finished!", Toast.LENGTH_SHORT).show()
            }
        }

        countDownTimer.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer.cancel()  // Always cancel the timer to avoid memory leaks.
    }
}

In the above example:

  • The countdown is set for 10,000 milliseconds (10 seconds).
  • The onTick() method will be called every 1,000 milliseconds (1 second).
  • The onFinish() method is called when the countdown is finished.

Remember to cancel the CountDownTimer in onDestroy() or other appropriate lifecycle methods to ensure no unwanted operations happen if the Activity is destroyed.

  1. Implementing CountDownTimer in Android Kotlin:

    • Description: CountDownTimer is a class in Android that allows you to create a timer that counts down to zero. It's useful for scenarios where you need to perform actions or update UI elements based on a specific time duration.
    • Code (Kotlin):
      // Example of implementing CountDownTimer
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
          }
      
          override fun onFinish() {
              // Perform actions when the countdown is finished
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  2. Creating a countdown timer in Android:

    • Description: Creating a countdown timer involves instantiating the CountDownTimer class and specifying the total duration and interval for each tick. You can then define actions to be executed on each tick and when the countdown finishes.
    • Code (Kotlin):
      // Example of creating a countdown timer
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
          }
      
          override fun onFinish() {
              // Perform actions when the countdown is finished
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  3. CountDownTimer for countdown functionality in Android:

    • Description: CountDownTimer is specifically designed for countdown functionality. It allows you to set a countdown duration and execute code at regular intervals until the countdown reaches zero.
    • Code (Kotlin):
      // Example of using CountDownTimer for countdown
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
          }
      
          override fun onFinish() {
              // Perform actions when the countdown is finished
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  4. Customizing CountDownTimer appearance in Android:

    • Description: While CountDownTimer itself doesn't have a visual appearance, you can customize its behavior and appearance by updating UI elements, such as TextViews, during each tick.
    • Code (Kotlin):
      // Example of updating a TextView with CountDownTimer
      val textView = findViewById<TextView>(R.id.textView)
      
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update the TextView with the remaining time
              textView.text = "Time remaining: ${millisUntilFinished / 1000} seconds"
          }
      
          override fun onFinish() {
              textView.text = "Countdown finished!"
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  5. Handling events with CountDownTimer in Android:

    • Description: CountDownTimer provides onTick and onFinish events that you can handle to perform actions at specified intervals during the countdown.
    • Code (Kotlin):
      // Example of handling events with CountDownTimer
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
          }
      
          override fun onFinish() {
              // Perform actions when the countdown is finished
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  6. Updating UI with CountDownTimer in Android:

    • Description: CountDownTimer can be used to update UI elements, such as progress bars or text views, during the countdown. This ensures a responsive and dynamic user interface.
    • Code (Kotlin):
      // Example of updating UI with CountDownTimer
      val progressBar = findViewById<ProgressBar>(R.id.progressBar)
      
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update the progress bar based on the remaining time
              val progress = (millisUntilFinished / 1000).toInt()
              progressBar.progress = progress
          }
      
          override fun onFinish() {
              progressBar.progress = 0
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
  7. Pausing and resuming CountDownTimer in Android:

    • Description: While CountDownTimer doesn't have built-in methods for pausing and resuming, you can achieve this functionality by canceling the current timer and starting a new one with the remaining time.
    • Code (Kotlin):
      // Example of pausing and resuming CountDownTimer
      val countDownTimer = object : CountDownTimer(60000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
          }
      
          override fun onFinish() {
              // Perform actions when the countdown is finished
          }
      }
      
      // Start the countdown timer
      countDownTimer.start()
      
      // Pause the countdown timer
      countDownTimer.cancel()
      
      // Resume the countdown timer with the remaining time
      countDownTimer.start()
      
  8. Countdown timer for game development in Android:

    • Description: CountDownTimer is commonly used in game development to create time-limited challenges or events. It allows you to implement countdowns for tasks, rounds, or specific game events.
    • Code (Kotlin):
      // Example of using CountDownTimer in game development
      val countDownTimer = object : CountDownTimer(30000, 1000) {
          override fun onTick(millisUntilFinished: Long) {
              // Update UI or perform actions on each tick
              updateGameUI(millisUntilFinished)
          }
      
          override fun onFinish() {
              // Perform actions when the game timer is finished
              endGame()
          }
      }
      
      // Start the game countdown timer
      countDownTimer.start()