SoFunction
Updated on 2025-04-09

Example of stopwatch timer implemented by Android

This article describes the stopwatch timer implemented by Android. Share it for your reference, as follows:

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class MyTime extends Activity {
  private long mlCount = 0;
  private long mlTimerUnit = 100;
  private TextView tvTime;
  private ImageButton btnStartPause;
  private ImageButton btnStop;
  private Timer timer = null;
  private TimerTask task = null;
  private Handler handler = null;
  private Message msg = null;
  private boolean bIsRunningFlg = false;
  private static final String MYTIMER_TAG = "MYTIMER_LOG";
  // menu item
  private static final int SETTING_TIMER_UNIT_ID = ;
  private static final int ABOUT_ID =  + 1;
  private static final int EXIT_ID =  + 2;
  private static final int SETTING_SECOND_ID =  + 101;
  private static final int SETTING_100MILLISECOND_ID =  + 102;
  // Setting timer unit flag
  private int settingTimerUnitFlg = SETTING_100MILLISECOND_ID;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    tvTime = (TextView) findViewById();
    btnStartPause = (ImageButton) findViewById();
    btnStop = (ImageButton) findViewById();
    SharedPreferences sharedPreferences = getSharedPreferences(
        "mytimer_unit", Context.MODE_PRIVATE);
    // The second parameter of getString() is the default value. If the key does not exist in the preference, the default value will be returned.    mlTimerUnit = ("time_unit", 100);
    (MYTIMER_TAG, "mlTimerUnit = " + mlTimerUnit);
    if (1000 == mlTimerUnit) {
      // second
      settingTimerUnitFlg = SETTING_SECOND_ID;
      (.init_time_second);
    } else if (100 == mlTimerUnit) {
      // 100 millisecond
      settingTimerUnitFlg = SETTING_100MILLISECOND_ID;
      (.init_time_100millisecond);
    }
    // Handle timer message
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        switch () {
        case 1:
          mlCount++;
          int totalSec = 0;
          int yushu = 0;
          if (SETTING_SECOND_ID == settingTimerUnitFlg) {
            // second
            totalSec = (int) (mlCount);
          } else if (SETTING_100MILLISECOND_ID == settingTimerUnitFlg) {
            // 100 millisecond
            totalSec = (int) (mlCount / 10);
            yushu = (int) (mlCount % 10);
          }
          // Set time display
          int min = (totalSec / 60);
          int sec = (totalSec % 60);
          try {
            if (SETTING_SECOND_ID == settingTimerUnitFlg) {
              // second(1000ms)
              (("%1$02d:%2$02d", min,
                  sec));
            } else if (SETTING_100MILLISECOND_ID == settingTimerUnitFlg) {
              // 100 millisecond
              (("%1$02d:%2$02d:%3$d",
                  min, sec, yushu));
            }
          } catch (Exception e) {
            ("" + min + ":" + sec + ":" + yushu);
            ();
            ("MyTimer onCreate", "Format string error.");
          }
          break;
        default:
          break;
        }
        (msg);
      }
    };
    (startPauseListener);
    (stopListener);
  }
  // Start and pause
   startPauseListener = new () {
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      (MYTIMER_TAG, "Start/Pause is clicked.");
      if (null == timer) {
        if (null == task) {
          task = new TimerTask() {
            @Override
            public void run() {
              // TODO Auto-generated method stub
              if (null == msg) {
                msg = new Message();
              } else {
                msg = ();
              }
               = 1;
              (msg);
            }
          };
        }
        timer = new Timer(true);
        (task, mlTimerUnit, mlTimerUnit); // set timer
      // duration
      }
      // start
      if (!bIsRunningFlg) {
        bIsRunningFlg = true;
        // ();
      } else { // pause
        try {
          bIsRunningFlg = false;
          ();
          task = null;
          (); // Cancel timer
          ();
          timer = null;
          ();
          // ();
        } catch (Exception e) {
          ();
        }
      }
    }
  };
  // Stop
   stopListener = new () {
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      (MYTIMER_TAG, "Stop is clicked.");
      if (null != timer) {
        ();
        task = null;
        (); // Cancel timer
        ();
        timer = null;
        ();
      }
      mlCount = 0;
      bIsRunningFlg = false;
      // ();
      if (SETTING_SECOND_ID == settingTimerUnitFlg) {
        // second
        (.init_time_second);
      } else if (SETTING_100MILLISECOND_ID == settingTimerUnitFlg) {
        // 100 millisecond
        (.init_time_100millisecond);
      }
    }
  };
  // Menu
  @Override
  public boolean onCreateOptionsMenu( menu) {
    // TODO Auto-generated method stub
    (menu);
    (MYTIMER_TAG, "Menu is created.");
    // Stop timer
    if (null != task) {
      ();
      task = null;
    }
    if (null != timer) {
      (); // Cancel timer
      ();
      timer = null;
      ();
    }
    bIsRunningFlg = false;
    mlCount = 0;
    // ();
    // Set the name of the submenu    // SubMenu settingMenu = (0, SETTING_TIMER_UNIT_ID, 0,
    // .menu_setting_timer_unit).setIcon();
    // Add submenu according to the corresponding name    // Sub menus do not support item icons, or nested sub menus.
    // (1, SETTING_SECOND_ID, 0,
    // .menu_setting_second);
    // (1, SETTING_100MILLISECOND_ID, 1,
    // .menu_setting_100milisec);
    // About
    // (0, ABOUT_ID, 1,
    // .menu_about).setIcon();
    // quit    // (0, EXIT_ID, 2, .menu_exit).setIcon();
    return true;
  }
  // Menu item
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    (MYTIMER_TAG, "Menu item is selected.");
    switch (()) {
    case SETTING_TIMER_UNIT_ID:
      break;
    case ABOUT_ID:
      // Display about dialog
       builder = new (this);
      (.app_name)
      .setMessage("This program was developed by Yumeng/nContact author: minyugong@")
      .setCancelable(true)
      .setPositiveButton("Sure", new () {
        public void onClick(DialogInterface dialog, int id) {
          ();
        }
      });
      AlertDialog alert = ();
      ();
      break;
    case EXIT_ID:
      finish(); // Exit application
      break;
    case SETTING_SECOND_ID: // Seconds (1000ms)      if (SETTING_SECOND_ID != settingTimerUnitFlg) {
        mlTimerUnit = 1000;
        settingTimerUnitFlg = SETTING_SECOND_ID;
      }
      (.init_time_second);
      break;
    case SETTING_100MILLISECOND_ID: // 100ms      if (SETTING_100MILLISECOND_ID != settingTimerUnitFlg) {
        mlTimerUnit = 100;
        settingTimerUnitFlg = SETTING_100MILLISECOND_ID;
      }
      (.init_time_100millisecond);
      break;
    default:
      (MYTIMER_TAG, "Other menu item...");
      break;
    }
    // Save timer unit
    try {
      SharedPreferences sharedPreferences = getSharedPreferences(
          "mytimer_unit", Context.MODE_PRIVATE);
       editor = ();// Get the editor      ("time_unit", mlTimerUnit);
      ();// Submit modification    } catch (Exception e) {
      ();
      (MYTIMER_TAG, "save timer unit error.");
    }
    return (item);
  }
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if (KeyEvent.KEYCODE_MENU == keyCode) {
      (); // Call this and the menu will pop up      (MYTIMER_TAG, "Menu key is clicked.");
      // Stop timer
      if (null != task) {
        ();
        task = null;
      }
      if (null != timer) {
        (); // Cancel timer
        ();
        timer = null;
        ();
      }
      bIsRunningFlg = false;
      mlCount = 0;
      // ();
      return true;
    }
    return (keyCode, event);
  }
}

For more information about Android related content, please check out the topic of this site:Android date and time operation skills summary》、《Android debugging skills and solutions to common problems》、《Android development introduction and advanced tutorial》、《Android multimedia operation skills summary (audio, video, recording, etc.)》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.