Android时分秒计时器的两种实现方法,Android实现的秒表计时器示例

可能我们在开发中会时常用到计时器这玩意儿,比如在录像的时候,我们可能需要在右上角显示一个计时器。这个东西其实实现起来非常简单。

冠亚体育手机网站,本文实例讲述了Android实现的秒表计时器。分享给大家供大家参考,具体如下:

只需要用一个控件Chronometer,是的,就这么简单,我都不好意思讲述一下了。

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);
  }
}
<Chronometer
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format="%s"
android:id="@+id/timer"/>

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

是的,就这么简单。java代码同样

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

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (Chronometer) findViewById(R.id.timer);
}
public void btnClick(View view) {
timer.setBase(SystemClock.elapsedRealtime());//计时器清零
timer.start();
}

您可能感兴趣的文章:

  • android之计时器(Chronometer)的使用以及常用的方法
  • android计时器,时间计算器的实现方法
  • android开发教程之间隔执行程序(android计时器)
  • Android 编程下的计时器代码
  • Android时分秒计时器的两种实现方法
  • Android编程之简单计时器实现方法
  • Android中CountDownTimer倒计时器用法实例
  • Android Wear计时器开发
  • 学习使用Android
    Chronometer计时器
  • Android利用SurfaceView实现简单计时器

超简单有木有?看看运行结果:

冠亚体育手机网站 1

或许你会说,这个要是需要显示上时间怎么弄呢?不急不急,两行代码就能解决的事情。

public void btnClick(View view) {
timer.setBase(SystemClock.elapsedRealtime());//计时器清零
int hour = (int) ((SystemClock.elapsedRealtime() - timer.getBase()) / 1000 / 60);
timer.setFormat("0"+String.valueOf(hour)+":%s");
timer.start();
}
public void stopClick(View view) {
timer.stop();
}

恩,对,就是 这么简单,不过别忘了把xml的format改一下

<Chronometer
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:format="00:00:00"
android:gravity="center"
android:id="@+id/timer"/>

是的,你没有看错,这样就可以了,不信,你看!

冠亚体育手机网站 2

就和你想象的录像上方的时间一样有木有?恩。你前面设置一个圆圈,再设置计时器颜色就和它一样有逼格了。

而或许你并不喜欢用这种方式,当然用handler+timer+timerTask的方式也是可以的啦。由于太简单,就直接上代码了。

package com.example.nanchen.timerdemo;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Chronometer;
import android.widget.TextView;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private Chronometer timer;
private Timer timer1;
private TextView textView;
private TimerTask timerTask;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (Chronometer) findViewById(R.id.timer);
textView = (TextView) findViewById(R.id.text);
timer1 = new Timer();
}
public void btnClick(View view) {
timer.setBase(SystemClock.elapsedRealtime());//计时器清零
int hour = (int) ((SystemClock.elapsedRealtime() - timer.getBase()) / 1000 / 60);
timer.setFormat("0"+String.valueOf(hour)+":%s");
timer.start();
}
public void stopClick(View view) {
timer.stop();
}
public void startClick(View view) {
timerTask = new TimerTask() {
int cnt = 0;
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(getStringTime(cnt++));
}
});
}
};
timer1.schedule(timerTask,0,1000);
}
private String getStringTime(int cnt) {
int hour = cnt/3600;
int min = cnt % 3600 / 60;
int second = cnt % 60;
return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second);
}
public void stopClick1(View view) {
if (!timerTask.cancel()){
timerTask.cancel();
timer1.cancel();
}
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.nanchen.timerdemo.MainActivity">
<Chronometer
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:format="00:00:00"
android:gravity="center"
android:id="@+id/timer"/>
<Button
android:layout_width="match_parent"
android:onClick="btnClick"
android:text="start"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:text="stop"
android:onClick="stopClick"
android:layout_height="wrap_content"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#959393"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="00:00:00"
android:gravity="center"
android:id="@+id/text"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始"
android:onClick="startClick"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止"
android:onClick="stopClick1"/>
</LinearLayout>

简单运行下方用timer实现的效果:

冠亚体育手机网站 3

想必大家到这样都会有了自己的理解,android
官方的Chronometer方式只是为了做一个计时器,而我们采用自己用Timer和TimerTask方式可以更加自主,因为你可以想从什么时间开始计时就从什么时间开始计时,计时方式想顺计时倒计时都不是难事儿,甚至各种浮夸的隔两秒,隔三秒,隔n秒都是可以的,具体使用就看你选择咯~~

以上所述是小编给大家介绍的Android时分秒计时器的两种实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

  • Android编程之计时器Chronometer简单示例
  • Android计时器的三种实现方式(Chronometer、Timer、handler)
  • Android
    Chronometer控件实现计时器函数详解
  • Android计时器chronometer使用实例讲解
  • 学习使用Android
    Chronometer计时器
  • android之计时器(Chronometer)的使用以及常用的方法
  • android计时器,时间计算器的实现方法
  • android开发教程之间隔执行程序(android计时器)
  • Android 编程下的计时器代码
  • Android计时器控件Chronometer应用实例

Post Author: admin

发表评论

电子邮件地址不会被公开。 必填项已用*标注