文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android实现的秒表计时器示例

2022-06-06 07:52

关注

本文实例讲述了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;
  
  @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程序设计有所帮助。

您可能感兴趣的文章:android之计时器(Chronometer)的使用以及常用的方法Android时分秒计时器的两种实现方法Android 编程下的计时器代码Android计时器的三种实现方式(Chronometer、Timer、handler)Android编程之简单计时器实现方法Android中CountDownTimer倒计时器用法实例Android Chronometer控件实现计时器函数详解Android计时器chronometer使用实例讲解Android开发实现的计时器功能示例


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯