欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现的秒表计时器示例

程序员文章站 2024-03-07 12:47:39
本文实例讲述了android实现的秒表计时器。分享给大家供大家参考,具体如下: package com.liu.time; import java.util.t...

本文实例讲述了android实现的秒表计时器。分享给大家供大家参考,具体如下:

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 when the activity is first created. */
  @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()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
    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 (100 == mltimerunit) {
      // 100 millisecond
      settingtimerunitflg = setting_100millisecond_id;
      tvtime.settext(r.string.init_time_100millisecond);
    }
    // handle timer message
    handler = new handler() {
      @override
      public void handlemessage(message 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) {
            // 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)
              tvtime.settext(string.format("%1$02d:%2$02d", min,
                  sec));
            } else if (setting_100millisecond_id == settingtimerunitflg) {
              // 100 millisecond
              tvtime.settext(string.format("%1$02d:%2$02d:%3$d",
                  min, sec, yushu));
            }
          } 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/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 = 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) {
        // 100 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);
    // 设置子菜单的名称
    // submenu settingmenu = menu.addsubmenu(0, setting_timer_unit_id, 0,
    // r.string.menu_setting_timer_unit).seticon(r.drawable.setting);
    // 按对应的名称增加子菜单
    // sub menus do not support item icons, 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);
    // 退出
    // 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 stub
    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("本程序由雨梦开发/n联系作者:minyugong@163.com")
      .setcancelable(true)
      .setpositivebutton("确定", 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: // 秒(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毫秒
      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_unit", context.mode_private);
      sharedpreferences.editor editor = sharedpreferences.edit();// 获取编辑器
      editor.putlong("time_unit", mltimerunit);
      editor.commit();// 提交修改
    } 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 (keyevent.keycode_menu == keycode) {
      super.openoptionsmenu(); // 调用这个,就可以弹出菜单
      log.i(mytimer_tag, "menu key is clicked.");
      // 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);
  }
}

更多关于android相关内容感兴趣的读者可查看本站专题:《android日期与时间操作技巧总结》、《android调试技巧与常见问题解决方法汇总》、《android开发入门与进阶教程》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。