本文实例为大家分享了Android计时器的三种方法,具体内容如下
目录:
1、借助Timer实现
2、调用handler.sendMessagedely(Message msg, long delayMillis)
3、借助布局Chronometer
1、借助Timer实现
(1) 布局文件
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/timerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="60sp" />
布局文件很简单,就是一个TextView用来显示计时时间。下面看一下Activity里的逻辑实现:
(2)Activity文件
public class MyChronometer extends Activity {
private TextView timerView;
private long baseTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.chrono);
MyChronometer.this.baseTimer = SystemClock.elapsedRealtime();
timerView = (TextView) this.findViewById(R.id.timerView);
final Handler startTimehandler = new Handler(){
public void handleMessage(android.os.Message msg) {
if (null != timerView) {
timerView.setText((String) msg.obj);
}
}
};
new Timer("开机计时器").scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
int time = (int)((SystemClock.elapsedRealtime() - MyChronometer.this.baseTimer) / 1000);
String hh = new DecimalFormat("00").format(time / 3600);
String mm = new DecimalFormat("00").form