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

Android Wear 計時器開發:設計思路與鬧鐘機制

編輯:關於 Android 程式設計

早在 2013 年 12 月,就曾有一系列文章介紹如何開發一款智慧手錶 App,讓使用者能在足球比賽中記錄停表時間。隨著 Android Wear 問世,在可穿戴裝置上打造這樣的應用確實是個不錯的想法,但依當時對 Android Wear 架構的了解,直接移植似乎頗有難度。於是這個系列就重寫了這款應用,帶大家一窺 Android Wear 的世界。

這個計時應用會在比賽開始時啟動,過程中可隨時暫停(停表),並在 45 分鐘(半場)與 90 分鐘(全場)時以震動提醒。

為什麼要重寫

智慧手錶採用的是修改版的 Android 系統,架構近似於運行早期 Android 的手機,因此 App 以單一 Activity 為核心。但必須先明白:手機那套設計在 Android Wear 上並不適用。雖然 Wear 也支援 Activity,但運作方式不同——在手機或平板上,Activity 從休眠回到喚醒會被重新叫起,而在 Wear 上,裝置休眠後,原本處於休眠的 Activity 並不會再被喚醒。

起初這讓我很驚訝:有了這個限制,還能做出實用的 App 嗎?後來發現完全是多慮了。關鍵在於轉變設計思維,讓軟體更貼合 Wear 的架構,而不是當它是手機。

省電的設計哲學

最基本但也最重要的問題是:計時應用需要一個「一直運行」的服務來記錄時間嗎?其實不必。長時間運行的服務很耗電,而我們真正需要的只是「使用者在看時能更新顯示」。大部分時間使用者只關心大概過了多久,只有在暫停或半場、全場結束前才需要精確到秒。因此絕大多數時候只顯示到分鐘即可,需要時再精確到秒。

實作方式是:用 AlarmManager 每分鐘觸發一次更新通知,刷新分鐘顯示;通知本身還包含一個能精確到秒的 Activity,但只有當使用者滑開通知時才會顯示。如此一來,只在必要時才更新,對大多數裝置而言,每分鐘更新一次比常駐服務省電得多。

下圖說明了這個概念:滑開通知後可看到精確到秒的顯示。

而在有通知或裝置休眠時,只顯示到分鐘即可。

另外要說明的是,App 名稱已從舊版的「Footy Timer」改為「Match Timer」。因為語音啟動時,Google 的語音辨識對「Footy」這個詞不敏感,用「ok Google,start Footy Timer」無法啟動,改用「ok Google,start Match Timer」就可以了。

核心狀態類別

我們先看控制計時器狀態的核心類別。它包含四個 long 變數:計時開始時間、計時停止時間(執行中則為 0)、本次停表時間(未停表則為 0),以及累計停表總時長。透過這四個變數就能維持狀態並計算出所需的顯示資訊。

public final class MatchTimer {
public static final int MINUTE_MILLIS = 60000;
private long start;
private long currentStoppage;
private long totalStoppages;
private long end;
public long getElapsed() {
  if (isRunning()) { return System.currentTimeMillis() - start; }
  if (end > 0) { return end - start; }
  return 0;
}
public boolean isRunning() { return start > 0 && end == 0; }
public boolean isPaused() { return currentStoppage > 0; }
public int getElapsedMinutes() { return (int) ((System.currentTimeMillis() - start) / MINUTE_MILLIS); }
public long getTotalStoppages() {
  long now = System.currentTimeMillis();
  if (isPaused()) { return totalStoppages + (now - currentStoppage); }
  return totalStoppages;
}
public long getPlayed() { return getElapsed() - getTotalStoppages(); }
public long getStartTime() { return start; }
}

操作狀態的方法如下:

public void start() { if (end > 0) { start = System.currentTimeMillis() - (end - start); end = 0; } else { start = System.currentTimeMillis(); } save(); }
public void stop() { if (isPaused()) { resume(); } end = System.currentTimeMillis(); save(); }
public void pause() { currentStoppage = System.currentTimeMillis(); save(); }
public void resume() { totalStoppages += System.currentTimeMillis() - currentStoppage; currentStoppage = 0L; save(); }
public void reset() { resetWithoutSave(); save(); }

用 SharedPreferences 保存狀態

由於我們不需要維持長連接或背景服務,只要保存這幾個計時器狀態即可,因此採用 SharedPreferences:

public final class MatchTimer implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String KEY_START = "com.stylingandroid.matchtimer.KEY_START";
private static final String KEY_CURRENT_STOPPAGE = "com.stylingandroid.matchtimer.KEY_CURRENT_STOPPAGE";
private static final String KEY_TOTAL_STOPPAGES = "com.stylingandroid.matchtimer.KEY_TOTAL_STOPPAGES";
private static final String KEY_END = "com.stylingandroid.matchtimer.KEY_END";
private static final String PREFERENCES = "MatchTimer";
private final SharedPreferences preferences;
public static MatchTimer newInstance(Context context) {
  SharedPreferences preferences = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
  long start = preferences.getLong(KEY_START, 0);
  long currentStoppage = preferences.getLong(KEY_CURRENT_STOPPAGE, 0);
  long totalStoppages = preferences.getLong(KEY_TOTAL_STOPPAGES, 0);
  long end = preferences.getLong(KEY_END, 0);
  return new MatchTimer(preferences, start, currentStoppage, totalStoppages, end);
}
public void save() {
  preferences.edit()
   .putLong(KEY_START, start)
   .putLong(KEY_CURRENT_STOPPAGE, currentStoppage)
   .putLong(KEY_TOTAL_STOPPAGES, totalStoppages)
   .putLong(KEY_END, end)
   .apply();
}
public void registerForUpdates() { preferences.registerOnSharedPreferenceChangeListener(this); }
public void unregisterForUpdates() { preferences.unregisterOnSharedPreferenceChangeListener(this); }
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
  long value = sharedPreferences.getLong(key, 0L);
  if (key.equals(KEY_START)) { start = value; }
  else if (key.equals(KEY_END)) { end = value; }
  else if (key.equals(KEY_CURRENT_STOPPAGE)) { currentStoppage = value; }
  else if (key.equals(KEY_TOTAL_STOPPAGES)) { totalStoppages = value; }
}
}

我們用 newInstance() 從 SharedPreference 建構 MatchTimer,用 save() 保存狀態。此外,若某個物件持有 MatchTimer 引用,而其他物件改變了計時器狀態,就可能發生不一致,因此還需提供註冊與取消註冊方法,在偏好值變動時接收狀態更新。

定時喚醒機制

既然不用常駐服務,就得有一套定時喚醒機制。我們用 AlarmManager 定時觸發 Intent,再通知 BroadcastReceiver。之所以選 BroadcastReceiver 而非 IntentService,是因為我們的任務輕量且生命週期短,用 BroadcastReceiver 可免去每次都經歷 Service 的完整生命週期。

核心在 onReceive,需在此安排各種事件:

public class MatchTimerReceiver extends BroadcastReceiver {
public static final int MINUTE_MILLIS = 60000;
private static final long DURATION = 45 * MINUTE_MILLIS;
private static final Intent UPDATE_INTENT = new Intent(ACTION_UPDATE);
private static final Intent ELAPSED_ALARM = new Intent(ACTION_ELAPSED_ALARM);
private static final Intent FULL_TIME_ALARM = new Intent(ACTION_FULL_TIME_ALARM);
private static final int REQUEST_UPDATE = 1;
private static final int REQUEST_ELAPSED = 2;
private static final int REQUEST_FULL_TIME = 3;
public static void setUpdate(Context context) { context.sendBroadcast(UPDATE_INTENT); }
private void resume(Context context, MatchTimer timer) { timer.resume(); long playedEnd = timer.getStartTime() + timer.getTotalStoppages() + DURATION; if (playedEnd > System.currentTimeMillis()) { setAlarm(context, REQUEST_FULL_TIME, FULL_TIME_ALARM, playedEnd); } }
private void pause(Context context, MatchTimer timer) { timer.pause(); cancelAlarm(context, REQUEST_FULL_TIME, FULL_TIME_ALARM); long elapsedEnd = timer.getStartTime() + DURATION; if (!isAlarmSet(context, REQUEST_ELAPSED, ELAPSED_ALARM) && elapsedEnd > System.currentTimeMillis()) { setAlarm(context, REQUEST_ELAPSED, ELAPSED_ALARM, elapsedEnd); } }
private void stop(Context context, MatchTimer timer) { timer.stop(); cancelAlarm(context, REQUEST_UPDATE, UPDATE_INTENT); cancelAlarm(context, REQUEST_ELAPSED, ELAPSED_ALARM); cancelAlarm(context, REQUEST_FULL_TIME, FULL_TIME_ALARM); }
}

這個 Receiver 共處理八個事件:五個控制狀態(START、STOP、PAUSE、RESUME、RESET)、一個更新通知,以及兩個在 45 分鐘時震動提醒。這些控制方法主要做兩件事:設定 MatchTimer 狀態,以及設定對應的鬧鐘。

鬧鐘的設定沿用標準 AlarmManager 寫法:

private void setRepeatingAlarm(Context context, int requestCode, Intent intent) {
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), MINUTE_MILLIS, pendingIntent);
}
private boolean isAlarmSet(Context context, int requestCode, Intent intent) {
  return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE) != null;
}
private void setAlarm(Context context, int requestCode, Intent intent, long time) {
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
private void cancelAlarm(Context context, int requestCode, Intent intent) {
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE);
  if (pendingIntent != null) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); }
}

值得留意的是 setRepeatingAlarm():在 Wear 上,設備休眠後需要重新計算下一分鐘的邊界值,因此不能單純每 60 秒觸發一次,而是要在設備喚醒時重算並讓設備每分鐘只喚醒一次。對計時器而言,顯示的分鐘數可能比實際少約 1 分鐘,但由於顯示分鐘不要求高度即時(顯示秒時才需精確),這樣的取捨是可以接受的。

兩個提醒鬧鐘透過震動服務呈現不同的節奏:

private static final long[] ELAPSED_PATTERN = {0, 500, 250, 500, 250, 500};
private static final long[] FULL_TIME_PATTERN = {0, 1000, 500, 1000, 500, 1000};
private void elapsedAlarm(Context context) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(ELAPSED_PATTERN, -1); }
private void fullTimeAlarm(Context context) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(FULL_TIME_PATTERN, -1); }

最後透過自訂的 NotificationBuilder 建構通知並呈現給使用者:

private void updateNotification(Context context, MatchTimer timer) { NotificationBuilder builder = new NotificationBuilder(context, timer); Notification notification = builder.buildNotification(); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(NOTIFICATION_ID, notification); }

通知是 Wear 計時器的重點環節,需要一個自訂類別來建構,這會在後續文章深入說明。

Match Timer 可在 Google Play 下載:
https://play.google.com/store/apps/details?id=com.stylingandroid.matchtimer

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