Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 計時器:Chronometer 與 Handler+Timer+TimerTask 兩種方案

編輯:關於 Android 程式設計

開發中經常會用到計時器,比如在錄像時右上角顯示一個計時。這個功能其實實現起來非常簡單。

方案一:使用 Chronometer 控件

只需一個 Chronometer 控件即可:

<Chronometer
    android:id="@+id/timer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format="%s" />

Java 代碼同樣簡單:

@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();
}

看看運行結果:

如果想顯示「時」,只需兩行代碼:

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:id="@+id/timer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:format="00:00:00"
    android:gravity="center" />

這樣就實現了類似錄像界面頂部那種帶「時分秒」的計時效果:

在前面加一個圓形背景、再調整計時器顏色,就能做出更有質感的樣式。

方案二:Handler + Timer + TimerTask

如果你更喜歡自己掌控計時邏輯,用 Handler + Timer + TimerTask 也可以,代碼並不複雜:

package com.example.nanchen.timerdemo;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
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="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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:id="@+id/timer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:format="00:00:00"
        android:gravity="center" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btnClick"
        android:text="start" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="stopClick"
        android:text="stop" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:background="#959393" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="00:00:00" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="startClick"
        android:text="開始" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="stopClick1"
        android:text="停止" />
</LinearLayout>

用 Timer 實現的效果如下:

兩種方案的取捨

官方的 Chronometer 方式只用於做一個簡單計時器,而自己用 Timer 和 TimerTask 則更加自主:你可以任意選擇從哪個時刻開始計時,順計時、倒計時都不在話下,甚至各種「隔兩秒、隔三秒、隔 n 秒」的定時需求也能輕鬆實現。具體選用哪種,取決於你的實際場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved