編輯:關於 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 的消息管理、以及數據持久化時機的選擇,才是決定一個功能是否健壯的關鍵。
善用 GCM 網路管理器(GcmNetworkManager)優化 Android 電池續航
GCM 網路管理器能讓 App 註冊可執行面向網路的服務,每個任務只需完成一項工作。它的 API 負責處理這些任務,讓 Google Play Services 透過系統
Android 通訊錄實戰(三):短信讀取與發送的完整實現
在這個系列的前兩篇文章裡,我們已經分別談過如何取得手機裡的聯絡人以及通話紀錄。到了第三篇,終於要來啃最硬的一塊骨頭——短信。之所以說它是通訊管理中的難點,是因為短信同時牽
Android 三種定位方式實作與比較
近來研究了 Android 的定位方式,查閱了不少資料並實際拿手機測試,以下是我的整理。 Android 一共有三種定位方式:GPS 定位、網路定位,以及基於基站的定位。
靠譜助手安裝失敗,提示需要 .NET 2.0 或 4.0 怎麼辦
安裝靠譜助手時跳出視窗,說需要 .NET Framework 2.0 或 .NET Framework 4.0——這代表系統裡沒有安裝對應的執行環境。把缺的補齊就能正常安