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

Android 實戰:動手做一個多功能時鐘(時鐘/鬧鐘/計時器/秒表)

編輯:關於 Android 程式設計

零散的知識點只有在真正動手組裝成一個完整功能時,才會暴露出真正的難點。本文記錄一個多功能時鐘應用的完整實現過程,四個模塊分別是實時時鐘、鬧鐘、倒計時計時器與秒表。

一、整體結構與佈局

界面借鑑系統時鐘的組織方式,採用 TabHost 承載四個頁面。外層是一個 FrameLayout,內部放入 TabHost,再依次填充自定義的內容佈局:

<FrameLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <com.example.clock.TimeView
                    android:id="@+id/tabTime"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                <com.example.clock.AlarmView
                    android:id="@+id/tabAlarm"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                <com.example.clock.TimerView
                    android:id="@+id/tabTimer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                <com.example.clock.StopWatchView
                    android:id="@+id/tabStopWatch"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</FrameLayout>

初學者看到 <com.example.clock.TimeView> 可能會疑惑這是什麼。它其實是自定義控件的引用方式——這四個類都繼承自 LinearLayout,在佈局中直接以全限定類名的形式使用即可。四個這樣的標簽,就對應四個 Tab 頁面。

MainActivity 的核心工作是配置 TabHost:

private TabHost tabHost;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tabHost = (TabHost) findViewById(android.R.id.tabhost);
    tabHost.setup();

    // newTabSpec 指定標簽 id,用於區分不同標簽
    // setIndicator 設置標簽名稱
    // setContent 設置標簽內容,可以是 View、Activity 或 Fragment
    tabHost.addTab(tabHost.newTabSpec("tabTime")
        .setIndicator("時鐘").setContent(R.id.tabTime));
    tabHost.addTab(tabHost.newTabSpec("tabAlarm")
        .setIndicator("鬧鐘").setContent(R.id.tabAlarm));
    tabHost.addTab(tabHost.newTabSpec("tabTimer")
        .setIndicator("計時器").setContent(R.id.tabTimer));
    tabHost.addTab(tabHost.newTabSpec("tabStopWatch")
        .setIndicator("秒表").setContent(R.id.tabStopWatch));
}

二、時鐘模塊

界面只有一個 TextView,負責顯示當前時間並每秒刷新。這裡還多做了一層考慮:當用戶切換到別的 Tab 時,刷新就應該停下來,避免佔用資源。因此用 Handler 配合 msg.what 來控制刷新的開與關。

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 defStyle) {
        super(context, attrs, defStyle);
    }

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

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        // 切回本頁時重新啟動刷新,否則移除所有待處理消息
        if (visibility == View.VISIBLE) {
            timeHandler.sendEmptyMessage(0);
        } else {
            timeHandler.removeMessages(0);
        }
    }

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

    private Handler timeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            refreshTime();
            // 只有處於可見狀態時才繼續投递下一次刷新
            if (getVisibility() == View.VISIBLE) {
                timeHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };
}

這裡的 Handler 也可以用 Timer 的週期任務達到同樣效果。onFinishInflate() 在自定義佈局中必不可少——佈局膨脹完成後才能安全地 findViewById。

三、鬧鐘模塊

這一頁用 ListView 展示已添加的鬧鐘,配一個 ArrayAdapter:

private ArrayAdapter<AlarmData> adapter;

AlarmData 是自定義的數據類型,用於描述一條鬧鐘記錄:

// 自定義數據類型
private static class AlarmData {
    private long time = 0;
    private Calendar date;
    private String timeLabel = "";

    public AlarmData(long time) {
        this.time = time;
        date = Calendar.getInstance();
        date.setTimeInMillis(time);
        timeLabel = String.format("%d月%d日 %d:%d",
            date.get(Calendar.MONTH) + 1,
            date.get(Calendar.DAY_OF_MONTH),
            date.get(Calendar.HOUR_OF_DAY),
            date.get(Calendar.MINUTE));
    }

    public long getTime() { return time; }
    public String getTimeLabel() { return timeLabel; }
    // 用「分鐘級時間戳」作為唯一標識
    public int getId() { return (int) (getTime() / 1000 / 60); }

    @Override
    public String toString() { return getTimeLabel(); }
}

持久化:保存與讀取

如果只把數據放在內存裡,退出應用後鬧鐘就全部消失了。這裡選擇最輕量的 SharedPreferences,把各條記錄的時間戳用逗號拼成一個字符串存起來。

private static final String KEY_ALARM_LIST = "alarmlist";

private void saveAlarmList() {
    Editor editor = getContext().getSharedPreferences(
        AlarmView.class.getName(), Context.MODE_PRIVATE).edit();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < adapter.getCount(); i++) {
        sb.append(adapter.getItem(i).getTime()).append(",");
    }
    if (sb.length() > 1) {
        // 去掉末尾多餘的逗號
        editor.putString(KEY_ALARM_LIST, sb.toString().substring(0, sb.length() - 1));
    } else {
        editor.putString(KEY_ALARM_LIST, null);
    }
    editor.commit();
}

private void readSaveAlarmList() {
    SharedPreferences sp = getContext().getSharedPreferences(
        AlarmView.class.getName(), Context.MODE_PRIVATE);
    String content = sp.getString(KEY_ALARM_LIST, null);
    if (content != null) {
        for (String string : content.split(",")) {
            adapter.add(new AlarmData(Long.parseLong(string)));
        }
    }
}

添加鬧鐘

添加時彈出時間選擇框,選好後創建記錄並向系統註冊重複鬧鐘:

private void addAlarm() {
    Calendar c = Calendar.getInstance();
    new TPDiolog(getContext(), new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            // 若選擇的時間早於當前時間,則顺延到第二天
            if (System.currentTimeMillis() >= calendar.getTimeInMillis()) {
                calendar.setTimeInMillis(calendar.getTimeInMillis() + 24 * 60 * 60 * 1000);
            }

            AlarmData ad = new AlarmData(calendar.getTimeInMillis());
            adapter.add(ad);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, ad.getTime(),
                5 * 60 * 1000,
                PendingIntent.getBroadcast(getContext(), ad.getId(),
                    new Intent(getContext(), AlarmReceiver.class), 0));
            saveAlarmList();
        }
    }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
}

這裡有一個容易踩的坑:直接使用系統的 TimePickerDialog,點擊「確定」會觸發一次 onTimeSet,而關閉對話框時又會再觸發一次,導致同一個鬧鐘被添加了兩條。解法是繼承該類並覆寫 onStop():

public class TPDiolog extends TimePickerDialog {
    public TPDiolog(Context context, OnTimeSetListener callBack,
                    int hourOfDay, int minute, boolean is24HourView) {
        super(context, callBack, hourOfDay, minute, is24HourView);
    }

    // 覆寫該方法以避免 onTimeSet 被調用兩次
    @Override
    protected void onStop() {
        // 不調用 super.onStop()
    }
}

alarmManager 是系統鬧鐘服務的實例,需要在初始化時取得。到點後由廣播接收者接手:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.cancel(PendingIntent.getBroadcast(context, getResultCode(),
            new Intent(context, AlarmReceiver.class), 0));

        Intent i = new Intent(context, PlayAlarmAty.class);
        // 從廣播接收者啟動 Activity 必須加上 NEW_TASK 標誌
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

刪除鬧鐘時,除了從 adapter 移除並重新持久化,還要記得調用 alarmManager.cancel() 撤銷已註冊的鬧鐘,否則到點仍會響。

四、計時器模塊

計時器的邏輯是:先設定時、分、秒,點擊開始後每秒遞減,歸零時彈出提示。核心用 Timer 加 TimerTask 完成。

private void startTimer() {
    if (timerTask == null) {
        allTimeCount = Integer.parseInt(etHour.getText().toString()) * 60 * 60
                     + Integer.parseInt(etMin.getText().toString()) * 60
                     + Integer.parseInt(etSec.getText().toString());
        timerTask = new TimerTask() {
            @Override
            public void run() {
                allTimeCount--;
                handle.sendEmptyMessage(MSG_WHAT_TIME_TICK);
                if (allTimeCount <= 0) {
                    handle.sendEmptyMessage(MSG_WHAT_TIME_IS_UP);
                    stopTimer();
                }
            }
        };
        timer.schedule(timerTask, 1000, 1000);
    }
}

private void stopTimer() {
    if (timerTask != null) {
        timerTask.cancel();
        timerTask = null;
    }
}

private Handler handle = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case MSG_WHAT_TIME_TICK:
                etHour.setText((allTimeCount / 60 / 60) + "");
                etMin.setText((allTimeCount / 60 % 60) + "");
                etSec.setText((allTimeCount % 60) + "");
                break;
            case MSG_WHAT_TIME_IS_UP:
                new AlertDialog.Builder(getContext())
                    .setTitle("Time is up!")
                    .setMessage("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;
        }
    }
};

輸入框需要限制範圍,這裡給時、分、秒三個 EditText 都掛上 TextWatcher,超出 59 就回寫為 59,並順帶判斷是否該啟用「開始」按鈕:

etMin.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // 在原有文本 s 中,從 start 開始的 count 個字符替換了長度為 before 的舊文本
        if (!TextUtils.isEmpty(s)) {
            int value = Integer.parseInt(s.toString());
            if (value > 59) {
                etMin.setText("59");
            } else if (value < 0) {
                etMin.setText("00");
            }
        }
        checkToEnableBtnStart();
    }
    @Override public void beforeTextChanged(CharSequence s, int a, int b, int c) { }
    @Override public void afterTextChanged(Editable s) { }
});

private void checkToEnableBtnStart() {
    btnStart.setEnabled(
        (!TextUtils.isEmpty(etHour.getText()) && Integer.parseInt(etHour.getText().toString()) > 0)
     || (!TextUtils.isEmpty(etMin.getText()) && Integer.parseInt(etMin.getText().toString()) > 0)
     || (!TextUtils.isEmpty(etSec.getText()) && Integer.parseInt(etSec.getText().toString()) > 0));
}

按鈕狀態通過 setVisibility 在開始/暫停/繼續/重置之間切換,交互邏輯比較直白,這裡不再展開。

五、秒表模塊

秒表用到 precision 到 0.1 秒(以 10 毫秒為計時單位),支持計次。它綜合了前面三個模塊的思路:Timer 計時 + Handler 刷新界面 + ListView 記錄計次。

private void startTimer() {
    if (timerTask == null) {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                tenMSecs++;
            }
        };
        timer.schedule(timerTask, 10, 10);
    }
}

private void stopTimer() {
    if (timerTask != null) {
        timerTask.cancel();
        timerTask = null;
    }
}

private Handler handle = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case MSG_WHAT_SHOW_TIME:
                tvHour.setText((tenMSecs / 100 / 60 / 60) + "");
                tvMin.setText((tenMSecs / 100 / 60 % 60) + "");
                tvSec.setText((tenMSecs / 100 % 60) + "");
                tvMsec.setText((tenMSecs % 100) + "");
                break;
            default:
                break;
        }
    }
};

// 計次按鈕:把當前用時插入列表頭部
btnLap.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        adapter.insert(String.format("%d:%d:%d.%d",
            tenMSecs / 100 / 60 / 60,
            tenMSecs / 100 / 60 % 60,
            tenMSecs / 100 % 60,
            tenMSecs % 100), 0);
    }
});

@Override
public void onDestroy() {
    timer.cancel();
}

這裡有個值得優化的細節:計時任務每 10 毫秒運行一次,而界面刷新任務每 200 毫秒才發一次消息。把「計數」與「繪製」解耦,能避免高頻更新 UI 帶來的開銷。

六、小結

第一個完整實戰至此完成。功能上四個模塊都跑通了,但界面還比較粗糙,交互細節也留有不少改進空間——比如鬧鐘可以支持重複周期與自定義鈴聲,計時器可以在後台由 Service 接管,秒表的刷新率可以做成可配置。這些都是後續迭代的方向。

回頭看,這次實戰最大的收穫不是某個 API 的用法,而是意識到:自定義 View 的生命週期方法(onFinishInflate、onVisibilityChanged)、Handler 的消息管理、以及數據持久化時機的選擇,才是決定一個功能是否健壯的關鍵。

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