chronometer

Chronometer in Android

The Android Chronometer is a timer that can be used to count time starting at a certain point. The Android Chronometer can be used to count time in both directions (upward or downward). It is a TextView subclass that displays the count in TextView.

A chronometer is an Android class that implements a simple timer. A chronometer is TextView’s  Subclass. This class helps us in adding a timer to our app. You can specify a start time in the elapsedRealTime() timebase for the Timer to begin counting from.

Chronometer code in xml :

    <Chronometer
        android:id="@+id/chronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

Working of chronometer

The start method is used to start the chronometer. Before the chronometer can begin counting, you must first set the starting point of time by calling the setBase method and giving the starting point of time. Because Chronometer’s default base time is the time at which the start method is called, it starts counting from 0 by default if you don’t set base.

chronometer

Even if you use SystemClock.elapsedRealtime() as the base, counting will begin at 0. This is how the Chronometer determines its default base.

To stop the chronometer, use the stop method. The start and stop methods do not change the base, they simply start and stop the display of the count in the text view. That is, once started, the Chronometer never stops counting. However, you can reset the base by invoking setBase with a new starting point.

The chronometer timer displays time in “MM:SS” or “H:MM:SS” by defaultyou can change this by using the setFormat method.

Android Chronometer upward Countdown or Downward Countdown

By default, the chronometer counts upward. If you want to have a countdown chronometer, call the setCountDown method and pass true as the value. This function is useful for counting down from a future time. Assume you want to start counting down from tomorrow in your app. Then, first, set setCountDown to true and base to SystemClock. 10006060*24 = elapsedRealtime() + one day’s time in milliseconds

I’ll use an example to demonstrate how to use Android Chronometer:

The code given below is an example of a chronometer stopwatch that displays a chronometer and three buttons. The first button will be displayed as the START button and second button as a PAUSE button, and the third button as a RESET button. Once the Start button is clicked, the chronometer will start counting from the current time displaying time in seconds. On clicking the PAUSE button, the count will pause. On clicking the RESET button, the base will be reset to the current time again to start a new count. In this, we have implemented an Event listener ( OnChronometerTickListener{} ) which will reset the Chronometer after every seven seconds.

Step 1: Create a new project in Android studio.

Step 2: activity_main.xml--> activity_main.xml contain a Chronometer and three buttons for start and pause, and reset operation.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="#abcdef"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/START"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:onClick="startMeter"
        android:backgroundTint="@color/black"
        android:text="Start"
        android:textColor="@color/white"
        app:layout_constraintBaseline_toBaselineOf="@+id/PAUSE"
        app:layout_constraintEnd_toStartOf="@+id/PAUSE"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/PAUSE"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="14dp"
        android:layout_marginRight="14dp"
        android:textColor="@color/white"
        android:layout_marginBottom="176dp"
        android:backgroundTint="@color/black"
        android:onClick="pauseMeter"
        android:text="Pause"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/RESET"
        app:layout_constraintStart_toEndOf="@+id/START" />

    <Button
        android:id="@+id/RESET"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="6dp"
        android:layout_marginRight="6dp"
        android:textColor="@color/white"
        android:onClick="resetMeter"
        android:text="Reset"
        android:backgroundTint="@color/black"
        app:layout_constraintBaseline_toBaselineOf="@+id/PAUSE"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/PAUSE" />

    <Chronometer
        android:id="@+id/chronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="243dp"
        android:textColor="@color/black"
        android:textSize="60sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: In MainActivity.kt initialize variable and implement Chronometer and functions for buttons.

package com.sagar.chronometerorstopwatch

import android.os.Bundle
import android.os.SystemClock
import android.view.View
import android.widget.Chronometer
import android.widget.Chronometer.OnChronometerTickListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private var chronometer: Chronometer? = null
    private var pauseOffset: Long = 0
    private var running = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        chronometer = findViewById(R.id.chronometer)
        chronometer?.format = "Clock: %s"
        chronometer?.base = SystemClock.elapsedRealtime()
        chronometer?.onChronometerTickListener = OnChronometerTickListener { chronometer ->
            if (SystemClock.elapsedRealtime() - chronometer.base >= 7000) {
                chronometer.base = SystemClock.elapsedRealtime()
                Toast.makeText(this@MainActivity, "Developers Dome!", Toast.LENGTH_LONG).show()
            }
        }
    }

    fun startMeter(v: View?) {
        if (!running) {
            chronometer!!.base = SystemClock.elapsedRealtime() - pauseOffset
            chronometer!!.start()
            running = true
        }
    }

    fun pauseMeter(v: View?) {
        if (running) {
            chronometer!!.stop()
            pauseOffset = SystemClock.elapsedRealtime() - chronometer!!.base
            running = false
        }
    }

    fun resetMeter(v: View?) {
        chronometer!!.base = SystemClock.elapsedRealtime()
        pauseOffset = 0
    }
}
  • We hope that this guide will assist you in quickly creating a Chronometer in Android. If you have any problems, please post them in the comments section, we will gladly assist you.
  • The official document of Chronometer.

Leave a Reply