Rahul Varma Rahul Varma - 1 year ago 97
Android Question

stop watch logic

I want to develop a simple stop watch logic in android.

On clicking a list view the timer should start and on clicking the button the timer should stop. Can anyone please guide me. Any sample code will be of great help

Answer Source

Use the Stopwatch Class (For higher precision use System.nanoTime())

Add a Start() event and Stop() event on Button Presses. You'll need to update the UI so use a Thread/Handler Combination.

This should get you started.

EDIT: Added Code. (Nice Exercise! :) )

Use the Refresh_Rate to configure how often your UI is updated.

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener{

    final int MSG_START_TIMER = 0;
    final int MSG_STOP_TIMER = 1;
    final int MSG_UPDATE_TIMER = 2;

    Stopwatch timer = new Stopwatch();
    final int REFRESH_RATE = 100;

    Handler mHandler = new Handler()
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_START_TIMER:
                timer.start(); //start timer

            case MSG_UPDATE_TIMER:
                tvTextView.setText(""+ timer.getElapsedTime());
                mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second, 
                break;                                  //though the timer is still running
            case MSG_STOP_TIMER:
                mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
                timer.stop();//stop timer
                tvTextView.setText(""+ timer.getElapsedTime());


    TextView tvTextView;
    Button btnStart,btnStop;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        tvTextView = (TextView)findViewById(R.id.TextView01);

        btnStart = (Button)findViewById(R.id.Button01);
        btnStop= (Button)findViewById(R.id.Button02);


    public void onClick(View v) {
        if(btnStart == v)
        if(btnStop == v){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download