Android Chronometer

Chronometer Class that implements a simple timer

You can give it a start time in the 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.

Usage of Chronometer

main.xml

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello">
<chronometer android:id="@+id/chronometer" android:layout_gravity="center_horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content">
<button android:id="@+id/buttonstart" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start">
</button><button android:id="@+id/buttonstop" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Stop">
</button><button android:id="@+id/buttonreset" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Reset">
</button></chronometer></textview></linearlayout>

AndroidChronometer.java

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class AndroidChronometer extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
       Button buttonStart = (Button)findViewById(R.id.buttonstart);
       Button buttonStop = (Button)findViewById(R.id.buttonstop);
       Button buttonReset = (Button)findViewById(R.id.buttonreset);
      
       buttonStart.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.start();
   }});
      
       buttonStop.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.stop();
    
   }});
      
       buttonReset.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    myChronometer.setBase(SystemClock.elapsedRealtime());
   }});            
   }
}