Chronometer in Android | AndroidMonks

Chronometer in Android | AndroidMonks

Chronometer in Android is useful to implement a simple Timer. It is a subclass of TextView however holds a countdown or count up timer.

According to the Android Docs,

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

You can give it a start time in the SystemClock.elapsedRealtime() timebase, and it counts up from that, or if you don’t give it a base time, it will use the time at which you call start().

The timer can also count downward towards the base time by setting setCountDown(boolean) to true.

By default it will display the current timer value in the form “MM:SS” or “H:MM:SS”, or you can use setFormat(String)to format the timer value into an arbitrary string.

From the above definition it is clear as what a Chronometer is capable of. We will see how the basic implementation can be done and the steps required to implement on in our Application.

Chronometer – Basic Implementation

In order to create a Chrono-meter, we can make use of the Tag Chronometer like below.

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

Just like all the Views, the default attributes are layout_weight and layout_height. We can make use of all the attributes related to a View or a Viewgroup. Check here for list of attributes related to a View.

Additionally, there are two attributes that this View takes. They are

  • android:countDown – This specifies whether the Timer is going to count down or count up.
  • android:format – Format string: if specified, the Chronometer will display this string, with the first “%s” replaced by the current timer value in “MM:SS” or “H:MM:SS” form.

Chronometer – Public Methods

We will take a look at some of the public methods used frequently with Chronometer Class below.

  • isCountDown()

    returns a Boolean value, indicating if Chrono meter is counting down or not

  • isTheFinalCountDown()

    Indicates if this is the final countdown

  • setBase(long base)

    This is responsible for setting the time that the count-up timer is in reference to

  • setCountDown(boolean countDown)

    Set this view to count down to the base instead of counting up from it

  • setFormat(String format)

    Responsible for setting the format in string that the timer uses to display

  • start()

    Starts the timer

  • stop()

    Stops the timer

  • setOnChronometerTickListener(Chronometer.OnChronometerTickListener listener)

    Very important listener, which will get fired whenever the timer ticks!

Creating a Chronometer in our Android Application

Time to create our Chronometer application. We will be using the Android Studio IDE to create the app.

A lot of changes have been made to the Chronometer after API 28, where in the count down feature has been added. It is important to set the base properly, other the count down will happen below zero, which is not what you want to see.

In order to show how the count down and count up timer works, we will be creating both the timers in one activity. Choose a layout titled chronometer_layout.xml like below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Count Down"
        android:textSize="20dp" />

    <Chronometer
        android:id="@+id/count_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:countDown="true"
        android:textColor="#008800"
        android:textSize="40dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Count Up"
        android:textSize="20dp" />

    <Chronometer
        android:id="@+id/count_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#008800"
        android:textSize="40dp" />

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start"
        android:textSize="25dp" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop"
        android:textSize="25dp" />
</LinearLayout>

I have used 2 Buttons, start and stop which will start both the timers at the same time. One counts down while the other counts up.

Activity for Chronometer
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Time;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Toast;

public class ChronometerActivity extends AppCompatActivity {
   Chronometer chronometer_up;
   Chronometer chronometer_down;
   Button start;
   Button stop;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chronometer);
        chronometer_down = findViewById(R.id.count_down);
        chronometer_up = findViewById(R.id.count_up);
        chronometer_up.setBase(SystemClock.elapsedRealtime());
        chronometer_down.setBase(SystemClock.elapsedRealtime()+600000);
        start = findViewById(R.id.start);
        stop = findViewById(R.id.stop);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chronometer_down.start();
                chronometer_up.start();
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chronometer_down.stop();
                chronometer_up.stop();
                Toast.makeText(view.getContext(),"Up"+String.valueOf(chronometer_up.getText())+"Down:"+
                String.valueOf(chronometer_down.getText()),Toast.LENGTH_SHORT).show();
            }
        });
    }
}

In this simple activity, we are setting the base for Both the Count-up and Count-down timer. Countdown timer starts 10 minutes (i.e) 60000 milli seconds in advance. Hence, those numbers.

The resulting Application looks like below.

Chronometer Application
Chronometer Application

Drop in any comments you have below.

“Learn and Be Curious”

Also Read  10 Must Have Plugins for Android Studio(Bonus Included)

Leave a Comment

Your email address will not be published. Required fields are marked *