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

Android 計時器與時間計算器的實作方法

編輯:關於 Android 程式設計

需求是這樣的:初始顯示「00:00:00」,點擊開始後歸零並開始計時,如 10:28:34;點擊停止則暫停計時。

過程中踩過一個坑:使用 Calendar、DateFormat 的方式時,不設時區抓到的是本地時區時間(東八區就是 8),設成 GMT 標準時區又會變成 12 小時制,且設 24 小時制無效;無論怎麼加減小時都達不到從 00:00:00 開始的效果,計時還會到 12 小時就跳掉。

試遍各種時間設定法都無效後,最後決定自己寫一個「依秒數轉換時間格式字串」的方法,測試後完全可行。要注意兩位數最多顯示到 99 小時,若要顯示更大時數需自行調整;小時數也不能無限大,超過 long 型別長度會變負數而發生異常。

顯示效果

測試類

public class TestTime {
    public static void main(String[] args) {
        TestTime tt = new TestTime();
        tt.showTimeCount(99 * 3600000 + 75 * 1000);
    }

    // 時間計數器,最多只能到 99 小時,如需更大時數需改方法
    public String showTimeCount(long time) {
        System.out.println("time=" + time);
        if (time >= 360000000) {
            return "00:00:00";
        }
        String timeCount = "";
        long hourc = time / 3600000;
        String hour = "0" + hourc;
        hour = hour.substring(hour.length() - 2, hour.length());

        long minuec = (time - hourc * 3600000) / 60000;
        String minue = "0" + minuec;
        minue = minue.substring(minue.length() - 2, minue.length());

        long secc = (time - hourc * 3600000 - minuec * 60000) / 1000;
        String sec = "0" + secc;
        sec = sec.substring(sec.length() - 2, sec.length());

        timeCount = hour + ":" + minue + ":" + sec;
        System.out.println("timeCount=" + timeCount);
        return timeCount;
    }
}

實際範例(含開始/停止按鈕)

// 時間計數器,最多只能到 99 小時
public String showTimeCount(long time) {
    if (time >= 360000000) {
        return "00:00:00";
    }
    String timeCount = "";
    long hourc = time / 3600000;
    String hour = "0" + hourc;
    hour = hour.substring(hour.length() - 2, hour.length());

    long minuec = (time - hourc * 3600000) / 60000;
    String minue = "0" + minuec;
    minue = minue.substring(minue.length() - 2, minue.length());

    long secc = (time - hourc * 3600000 - minuec * 60000) / 1000;
    String sec = "0" + secc;
    sec = sec.substring(sec.length() - 2, sec.length());

    timeCount = hour + ":" + minue + ":" + sec;
    return timeCount;
}

private Handler stepTimeHandler;
private Runnable mTicker;
long startTime = 0;

// 開始按鈕
class startBtnListener implements OnClickListener {
    @Override
    public void onClick(View v) {
        Button b = (Button) v;
        String buttonText = b.getText().toString();
        if ("Start".equalsIgnoreCase(buttonText)) {
            b.setText("Stop");
            // 清零 開始計時
            stepTimeTV.setText("00:00:00");
            stepTimeHandler = new Handler();
            startTime = System.currentTimeMillis();
            mTicker = new Runnable() {
                public void run() {
                    String content = showTimeCount(System.currentTimeMillis() - startTime);
                    stepTimeTV.setText(content);

                    long now = SystemClock.uptimeMillis();
                    long next = now + (1000 - now % 1000);
                    stepTimeHandler.postAtTime(mTicker, next);
                }
            };
            // 啟動計時,定時更新
            mTicker.run();
        } else {
            b.setText("Start");
            // 停止計時:移除訊息佇列中待處理的 Runnable
            stepTimeHandler.removeCallbacks(mTicker);
        }
    }
}

附錄:時間格式化方式的嘗試(無效)

以下是用 Calendar 與 DateFormat 的嘗試,因時區問題無法正常顯示 00:00:00,僅供參考:

// 透過 Calendar 時間設定,無法正常顯示小時為 0
class startBtnListener implements OnClickListener {
    @Override
    public void onClick(View v) {
        Button b = (Button) v;
        String buttonText = b.getText().toString();
        if ("Start".equalsIgnoreCase(buttonText)) {
            b.setText("Stop");
            stepTimeTV.setText("00:00:00");
            if (mCalendar == null) {
                mCalendar = Calendar.getInstance();
                TimeZone tz = TimeZone.getTimeZone("GMT");
                mCalendar.setTimeZone(tz);
                mCalendar.get(Calendar.HOUR_OF_DAY); // 24 小時制
            }
            stepTimeHandler = new Handler();
            // System.currentTimeMillis() 返回自 1970 到現在的毫秒數
            // 直接取的是當地時區時間,設 GMT 後始終多 12 小時
            startTime = System.currentTimeMillis();
            mTicker = new Runnable() {
                public void run() {
                    long showTime = System.currentTimeMillis() - startTime;
                    Log.i(TAG, showTime + "");
                    mCalendar.setTimeInMillis(showTime + 13 * 3600000 + 1000);
                    String content = (String) DateFormat.format(mFormat, mCalendar);
                    stepTimeTV.setText(content);

                    long now = SystemClock.uptimeMillis();
                    long next = now + (1000 - now % 1000);
                    stepTimeHandler.postAtTime(mTicker, next);
                }
            };
            mTicker.run();
        } else {
            b.setText("Start");
            stepTimeHandler.removeCallbacks(mTicker);
        }
    }
}

private Handler stepTimeHandler;
Calendar mCalendar;
String mFormat = "yyyy-MM-dd hh:mm:ss";
long startTime = 0;
private Runnable mTicker;

結論:與其和時區、格式化纏鬥,不如自己把毫秒差值換算成時、分、秒再拼字串,反而簡單可靠。搭配 Handler 的 postAtTime 每秒更新一次,並用 removeCallbacks 停止,就能做出一個精準的碼錶計時器。

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