Android implementation of the stopwatch timer sample _android

Source: Internet
Author: User
Tags commit set time stub

This example describes the stopwatch timer implemented by Android. Share to everyone for your reference, specific as follows:

Package com.liu.time;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.Context;
Import Android.content.DialogInterface;
Import android.content.SharedPreferences;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.Log;
Import android.view.KeyEvent;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.View;
Import Android.widget.ImageButton;
Import Android.widget.TextView;
  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 = Menu.first;
  private static final int about_id = Menu.first + 1;
  private static final int exit_id = Menu.first + 2;
  private static final int setting_second_id = Menu.first + 101;
  private static final int setting_100millisecond_id = Menu.first + 102;
  Setting timer Unit flag private int settingtimerunitflg = setting_100millisecond_id; /** called the activity is a.
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
    Tvtime = (TextView) Findviewbyid (r.id.tvtime);
    Btnstartpause = (ImageButton) Findviewbyid (r.id.btnstartpaunse);
    Btnstop = (ImageButton) Findviewbyid (r.id.btnstop);
    Sharedpreferences sharedpreferences = getsharedpreferences ("Mytimer_unit", context.mode_private);
    GetString () The second parameter is the default, and if the key does not exist in preference, the default value is returned Mltimerunit = Sharedpreferences.getlong ("Time_unit", 100); LOG.I (Mytimer_tag, "MltimerUnit = "+ Mltimerunit);
      if (1000 = = Mltimerunit) {//second SETTINGTIMERUNITFLG = setting_second_id;
    Tvtime.settext (R.string.init_time_second);
      else if (= = = Mltimerunit) {//millisecond SETTINGTIMERUNITFLG = setting_100millisecond_id;
    Tvtime.settext (R.string.init_time_100millisecond); 
        }//Handle timer Message Handler = new Handler () {@Override public void Handlemessage (msg) {
          TODO auto-generated Method Stub switch (msg.what) {case 1:mlcount++;
          int totalsec = 0;
          int Yushu = 0;
          if (setting_second_id = = SETTINGTIMERUNITFLG) {//SECOND totalsec = (int) (mlcount);  else if (setting_100millisecond_id = SETTINGTIMERUNITFLG) {//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) tvtime.set
            Text (String.Format ("%1$02d:%2$02d", Min, sec); else if (setting_100millisecond_id = SETTINGTIMERUNITFLG) {//Millisecond Tvtime.sette
            XT (String.Format ("%1$02d:%2$02d:%3$d", Min, sec, Yushu));
            The catch (Exception e) {tvtime.settext ("+ min +": "+ sec +": "+ Yushu);
            E.printstacktrace ();
          LOG.E ("MyTimer onCreate", "Format string error.");
        } break;
        Default:break;
      Super.handlemessage (msg);
    }
    };
    Btnstartpause.setonclicklistener (Startpauselistener);
  Btnstop.setonclicklistener (Stoplistener);
   }//Start and pause view.onclicklistener startpauselistener = new View.onclicklistener () { @Override public void OnClick (View v) {//TODO auto-generated Method Stub log.i (Mytimer_tag, "Start/paus
      E is clicked. "); if (null = = timer) {if (null = Task) {task = new TimerTask () {@Override Publ IC void Run () {//TODO auto-generated method stub if (null = msg) {msg = NE
              W message ();
              else {msg = Message.obtain ();
              } msg.what = 1;
            Handler.sendmessage (msg);
        }
          };
        Timer = new timer (true); Timer.schedule (Task, Mltimerunit, mltimerunit);
        Set timer//Duration}//start if (!BISRUNNINGFLG) {BISRUNNINGFLG = true;
      Btnstartpause.setimageresource (R.drawable.pause);
          else {//pause try {bisrunningflg = false;
          Task.cancel ();
          task = null; Timer.cancel (); CancEl timer Timer.purge ();
          timer = null;
          Handler.removemessages (Msg.what);
        Btnstartpause.setimageresource (R.drawable.start);
        catch (Exception e) {e.printstacktrace ();
  }
      }
    }
  }; 
      Stop View.onclicklistener Stoplistener = new View.onclicklistener () {@Override public void OnClick (View v) {
      TODO auto-generated Method Stub log.i (Mytimer_tag, "Stop is clicked.");
        if (null!= timer) {task.cancel ();
        task = null; Timer.cancel ();
        Cancel timer timer.purge ();
        timer = null;
      Handler.removemessages (Msg.what);
      } mlcount = 0;
      BISRUNNINGFLG = false;
      Btnstartpause.setimageresource (R.drawable.start);
      if (setting_second_id = = SETTINGTIMERUNITFLG) {//SECOND Tvtime.settext (R.string.init_time_second); else if (setting_100millisecond_id = SETTINGTIMERUNITFLG) {//millisecond
        Tvtime.settext (R.string.init_time_100millisecond);
  }
    }
  };
    Menu @Override Public boolean oncreateoptionsmenu (Android.view.Menu menu) {//TODO auto-generated method stub
    Super.oncreateoptionsmenu (menu);
    LOG.I (Mytimer_tag, "menu is created.");
      Stop timer if (null!= Task) {task.cancel ();
    task = null;
      } if (null!= timer) {timer.cancel ();//Cancel Timer timer.purge ();
      timer = null;
    Handler.removemessages (Msg.what);
    } BISRUNNINGFLG = false;
    Mlcount = 0;
    Btnstartpause.setimageresource (R.drawable.start); Set the name of the submenu//submenu Settingmenu = Menu.addsubmenu (0, setting_timer_unit_id, 0,//R.string.menu_setting_timer_u
    NIT). SetIcon (r.drawable.setting);
    Increase the submenu/Sub menus does not support item icons by the corresponding name, or nested sub menus.
    Settingmenu.add (1, setting_second_id, 0,//R.string.menu_setting_second); Settingmenu.add (1, Setting_100milliseconD_ID, 1,//R.STRING.MENU_SETTING_100MILISEC);
    About//menu.add (0, about_id, 1,//R.string.menu_about). SetIcon (R.drawable.about);
    Exit//Menu.add (0, exit_id, 2, R.string.menu_exit). SetIcon (R.drawable.exit);
  return true; }//Menu Item @Override Public boolean onoptionsitemselected (MenuItem Item) {//TODO auto-generated method Stu
    b log.i (Mytimer_tag, "menu item is selected.");
    Switch (Item.getitemid ()) {case setting_timer_unit_id:break;
      Case ABOUT_ID://Display About dialog Alertdialog.builder Builder = new Alertdialog.builder (this);
      Builder.settitle (R.string.app_name). Setmessage ("This procedure is developed by the rain Dream/n Contact Author: minyugong@163.com"). Setcancelable (True) . Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {public void OnClick (dialoginterface dialog, int
        ID) {dialog.cancel ();
      }
      });
      Alertdialog alert = Builder.create ();
      Alert.show (); BreAk Case Exit_id:finish ();
    Exit application break;
        Case SETTING_SECOND_ID://sec (1000ms) if (setting_second_id!= settingtimerunitflg) {mltimerunit = 1000;
      SETTINGTIMERUNITFLG = setting_second_id;
      } tvtime.settext (R.string.init_time_second);
    Break  Case SETTING_100MILLISECOND_ID://100 ms if (setting_100millisecond_id!= settingtimerunitflg) {Mltimerunit
        = 100;
      SETTINGTIMERUNITFLG = setting_100millisecond_id;
      } tvtime.settext (R.string.init_time_100millisecond);
    Break
      DEFAULT:LOG.I (Mytimer_tag, "other menu item ...");
    Break }//Save timer unit try {sharedpreferences sharedpreferences = getsharedpreferences ("Mytimer_un
      It ", context.mode_private);
      Sharedpreferences.editor Editor = Sharedpreferences.edit ();//Get Editor Editor.putlong ("Time_unit", mltimerunit); Editor.commit ()//Commit modification} catch (Exception e) {E.PRIntstacktrace ();
    LOG.E (Mytimer_tag, "Save timer Unit error.");
  return super.onoptionsitemselected (item); @Override public boolean onKeyDown (int keycode, keyevent event) {//TODO auto-generated Method stub if (Key Event.keycode_menu = = keycode) {super.openoptionsmenu ();//Call this, you can pop-up menu log.i (Mytimer_tag, "Menu key is clic
      ked. ");
        Stop timer if (null!= Task) {task.cancel ();
      task = null;
        } if (null!= timer) {timer.cancel ();//Cancel Timer timer.purge ();
        timer = null;
      Handler.removemessages (Msg.what);
      } BISRUNNINGFLG = false;
      Mlcount = 0;
      Btnstartpause.setimageresource (R.drawable.start);
    return true;
  Return Super.onkeydown (KeyCode, event);

 }
}

For more information on Android-related content readers can view the site: "Android date and time Operation tips Summary", "Android debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", " Android Multimedia How-to Summary (audio, video, audio, etc), summary of Android Basic components usage, Android View tips Summary, Android layout layout tips and a summary of Android controls usage

I hope this article will help you with the Android program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.