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

Android 開發第六彈:動手做一個簡易時鐘與計時器

編輯:關於 Android 程式設計

接續上一篇的簡易時鐘(鬧鐘)。這次做時鐘與計時器,外觀一樣樸素,但功能齊全。

時鐘

先從最簡單的時鐘開始。顯示目前時間而已,若要換成世界各城市的時間,也只是在小時上加减幾個小時的事。

新增 TimeView 類並繼承 LinearLayout,版面寫法和上一篇如出一轍:

<com.myapplication.nomasp.com.clock.TimeView
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/tabTime"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTime"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</com.myapplication.nomasp.com.clock.TimeView>
public class TimeView extends LinearLayout {

    private TextView tvTime;

    public TimeView(Context context) {
        super(context);
    }

    public TimeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvTime.setText("00:00:00");
        timeHandler.sendEmptyMessage(0);
    }

    private Handler timeHandler = new Handler() {
        public void handleMessage(Message msg) {
            refreshTime();
            // 只有可見時才繼續排下一輪,避免不可見時空轉
            if (getVisibility() == View.VISIBLE) {
                timeHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    // 刷新時間
    private void refreshTime() {
        Calendar c = Calendar.getInstance();
        tvTime.setText(String.format("%d:%d:%d",
                c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE),
                c.get(Calendar.SECOND)));
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            timeHandler.sendEmptyMessage(0);
        } else {
            timeHandler.removeMessages(0);
        }
    }
}

這裡有兩個值得留意的細節。第一,用 onVisibilityChanged() 搭配 removeMessages(),讓 View 不可見時停止刷新,省電也避免無效更新。第二,String.format 的格式字串應該用 %02d 而不是 %d,這樣才會補零成 09:05:03 而不是 9:5:3。

計時器 TimerView

計時器同樣繼承 LinearLayout,版面多了一段輸入區與一排按鈕:

<com.myapplication.nomasp.com.clock.TimerView
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/tabTimer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/etHour"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/etMinute"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/etSecond"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/llBtnGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnStart"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/start" />

        <Button
            android:id="@+id/btnPause"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/pause" />

        <Button
            android:id="@+id/btnResume"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/resume" />

        <Button
            android:id="@+id/btnReset"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/reset" />
    </LinearLayout>
</com.myapplication.nomasp.com.clock.TimerView>

先把要用的欄位宣告好:

private Button btnStart, btnPause, btnResume, btnReset;
private EditText etHour, etMinute, etSecond;

private static final int MSG_WHAT_TIME_IS_UP = 1;
private static final int MSG_WHAT_TIME_TICK = 2;

// 剩餘需要倒數的總秒數
private int allTimerCount = 0;
private Timer timer = new Timer();
private TimerTask timerTask = null;

public TimerView(Context context) { super(context); }
public TimerView(Context context, AttributeSet attrs) { super(context, attrs); }
public TimerView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

接著在 onFinishInflate() 裡掛上各個按鈕的監聽。每個動作除了執行本身的功能,還要負責切換按鈕的顯示與隱藏——這是這段程式碼看起來比較長的原因。另外三個輸入框都套上 TextWatcher,把值鎖在 0 到 59 之間。

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    // 暫停
    btnPause = (Button) findViewById(R.id.btnPause);
    btnPause.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopTimer();
            btnPause.setVisibility(View.GONE);
            btnResume.setVisibility(View.VISIBLE);
        }
    });

    // 重置
    btnReset = (Button) findViewById(R.id.btnReset);
    btnReset.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopTimer();
            etHour.setText("0");
            etMinute.setText("0");
            etSecond.setText("0");
            btnReset.setVisibility(View.GONE);
            btnResume.setVisibility(View.GONE);
            btnPause.setVisibility(View.GONE);
            btnStart.setVisibility(View.VISIBLE);
        }
    });

    // 繼續
    btnResume = (Button) findViewById(R.id.btnResume);
    btnResume.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startTime();
            btnResume.setVisibility(View.GONE);
            btnPause.setVisibility(View.VISIBLE);
        }
    });

    // 開始
    btnStart = (Button) findViewById(R.id.btnStart);
    btnStart.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startTime();
            btnStart.setVisibility(View.GONE);
            btnPause.setVisibility(View.VISIBLE);
            btnReset.setVisibility(View.VISIBLE);
        }
    });

    etHour = (EditText) findViewById(R.id.etHour);
    etMinute = (EditText) findViewById(R.id.etMinute);
    etSecond = (EditText) findViewById(R.id.etSecond);

    etHour.setText("00");
    etHour.addTextChangedListener(clampWatcher(etHour));
    etMinute.setText("00");
    etMinute.addTextChangedListener(clampWatcher(etMinute));
    etSecond.setText("00");
    etSecond.addTextChangedListener(clampWatcher(etSecond));

    btnStart.setVisibility(View.VISIBLE);
    btnPause.setVisibility(View.GONE);
    btnResume.setVisibility(View.GONE);
    btnReset.setVisibility(View.GONE);
}

// 把「限制在 0~59」與「檢查能否開始」抽成一個方法,避免三處重複
private TextWatcher clampWatcher(final EditText et) {
    return new TextWatcher() {
        @Override public void beforeTextChanged(CharSequence s, int a, int b, int c) { }
        @Override public void afterTextChanged(Editable s) { }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!TextUtils.isEmpty(s)) {
                int value = Integer.parseInt(s.toString());
                if (value > 59) {
                    et.setText("59");
                } else if (value < 0) {
                    et.setText("0");
                }
            }
            checkToEnableBtnStart();
        }
    };
}

判斷能不能按下開始——三個輸入框至少要有一個大於 0:

// 判斷是否可以開始
private void checkToEnableBtnStart() {
    btnStart.setEnabled(
            (!TextUtils.isEmpty(etHour.getText())
                    && Integer.parseInt(etHour.getText().toString()) > 0)
            || (!TextUtils.isEmpty(etMinute.getText())
                    && Integer.parseInt(etMinute.getText().toString()) > 0)
            || (!TextUtils.isEmpty(etSecond.getText())
                    && Integer.parseInt(etSecond.getText().toString()) > 0));
}

於是就可以開始倒數了。這裡把時分秒換算成總秒數,再用 Timer 每秒觸發一次:

// 開始計時
private void startTime() {
    if (timerTask == null) {
        // 把三個輸入框換算成總秒數
        allTimerCount = Integer.parseInt(etHour.getText().toString()) * 60 * 60
                + Integer.parseInt(etMinute.getText().toString()) * 60
                + Integer.parseInt(etSecond.getText().toString());

        timerTask = new TimerTask() {
            @Override
            public void run() {
                allTimerCount--;
                handler.sendEmptyMessage(MSG_WHAT_TIME_TICK);
                // 倒數結束,通知 handler 收尾
                if (allTimerCount <= 0) {
                    handler.sendEmptyMessage(MSG_WHAT_TIME_IS_UP);
                    stopTimer();
                }
            }
        };
        // 延後 1 秒啟動,之後每 1 秒一次
        timer.schedule(timerTask, 1000, 1000);
    }
}

能開始,也要能停。

// 停止計時
private void stopTimer() {
    if (timerTask != null) {
        timerTask.cancel();
        timerTask = null;
    }
}

最後是 Handler,負責把秒數拆回時分秒並更新畫面,時間到時彈出提示:

private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_WHAT_TIME_TICK:
                int hour = allTimerCount / 60 / 60;
                int min = (allTimerCount / 60) % 60;
                int sec = allTimerCount % 60;
                etHour.setText(hour + "");
                etMinute.setText(min + "");
                etSecond.setText(sec + "");
                break;

            case MSG_WHAT_TIME_IS_UP:
                new AlertDialog.Builder(getContext())
                        .setTitle("Time is up")
                        .setMessage("Message: Time is up")
                        .setNegativeButton("Cancel", null)
                        .show();
                btnReset.setVisibility(View.GONE);
                btnResume.setVisibility(View.GONE);
                btnPause.setVisibility(View.GONE);
                btnStart.setVisibility(View.VISIBLE);
                break;

            default:
                break;
        }
    }
};

幾個可以再改的地方

這個版本能跑,但有幾處值得回頭收拾。

計時精度。 用 Timer 每秒減一,累積誤差會隨時間放大——因為每次排程都有延遲,而我們每次都少算一秒。比較穩的做法是記錄起始的 SystemClock.elapsedRealtime(),每次回呼時用「現在 − 起始」算出應該顯示的秒數,這樣就不會累積漂移。

Handler 與執行緒。 TimerTask 跑在自己的背景執行緒,透過 Handler 回主執行緒更新 UI 是對的。但 Handler 宣告在 onFinishInflate() 之前,若這個 View 被銷毀而計時仍在跑,回呼就會打到已無效的環境。實務上該在 onDetachedFromWindow() 裡呼叫 stopTimer() 並清掉 Handler 的訊息。

時間到之後的行為。 目前只是彈一個對話框。若要做成鬧鐘那樣能發通知、播放音效或震動,這裡就是擴充點。

下一篇是系列的最後一篇:簡易時鐘(秒表)。需要的完整程式碼可以在留言處留下信箱,我會寄給你。

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