編輯:進階開發
想在 Android 上做出一個可靠的鬧鐘,核心其實只有三件事:把鬧鐘登報給系統、讓系統在約定時間主動通知你、以及在通知抵達時決定要做什麼。本文以 Android 內建時鐘的 AlarmAlert 與 Alarms 類別為例,把整個環節拆開來看。
第一步:註冊鬧鐘。透過 AlarmManager 搭配 PendingIntent 與 Intent,把「幾點要響」這件事交給系統。
第二步:註冊鬧鐘廣播接收者。撰寫一個 BroadcastReceiver,負責接收時間到齊的訊號。
第三步:處理時間到的行為。例如拉開某個應用、跳提示視窗、播放鈴聲或啟動震動,端看你想怎麼提醒使用者。
鬧鐘響起時,使用者多半只有兩個選擇:關掉,或再睡一會兒。以下程式碼示範了「稍後再響」按鈕的綁定,以及貪睡時間的計算與保存。
private void updateLayout() {
// snooze behavior: pop a snooze confirmation view, kick alarm manager.
Button snooze = (Button) findViewById(R.id.snooze);
snooze.requestFocus();
snooze.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
snooze();
}
});
}
// Attempt to snooze this alert.
private void snooze() {
final String snooze = PreferenceManager.getDefaultSharedPreferences(this)
.getString(SettingsActivity.KEY_ALARM_SNOOZE, DEFAULT_SNOOZE);
int snoozeMinutes = Integer.parseInt(snooze);
final long snoozeTime = System.currentTimeMillis()
+ (1000 * 60 * snoozeMinutes); // 計算貪睡後的時間
Alarms.saveSnoozeAlert(AlarmAlert.this, mAlarm.id, snoozeTime); // 保存貪睡時間
// Get the display time for the snooze and update the notification.
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(snoozeTime);
// Notify the user that the alarm has been snoozed.
// 通知 AlarmReceiver.class,重新安排鬧鐘時間
Intent cancelSnooze = new Intent(this, AlarmReceiver.class);
cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
cancelSnooze.putExtra(Alarms.ALARM_ID, mAlarm.id);
PendingIntent broadcast =
PendingIntent.getBroadcast(this, mAlarm.id, cancelSnooze, 0);
NotificationManager nm = getNotificationManager();
stopService(new Intent(Alarms.ALARM_ALERT_ACTION));
finish();
}
按下貪睡之後,真正的重排工作交給 Alarms 類別處理。它把貪睡的識別碼與觸發時間寫進 SharedPreferences,再呼叫 setNextAlert() 重新計算下一次要響的時刻。
static void saveSnoozeAlert(final Context context, final int id, final long time) {
SharedPreferences prefs = context.getSharedPreferences(AlarmClock.PREFERENCES, 0);
SharedPreferences.Editor ed = prefs.edit();
if (id == -1) {
clearSnoozePreference(ed);
} else {
ed.putInt(PREF_SNOOZE_ID, id);
ed.putLong(PREF_SNOOZE_TIME, time); // 保存提醒時間
ed.commit();
}
// Set the next alert after updating the snooze.
setNextAlert(context);
}
/**
* If there is a snooze set, enable it in AlarmManager.
* @return true if snooze is set
*/
private static boolean enableSnoozeAlert(final Context context) {
SharedPreferences prefs = context.getSharedPreferences(AlarmClock.PREFERENCES, 0);
int id = prefs.getInt(PREF_SNOOZE_ID, -1);
if (id == -1) {
return false;
}
long time = prefs.getLong(PREF_SNOOZE_TIME, -1); // 取出設定好的鬧鐘時間
// Get the alarm from the db.
final Alarm alarm = getAlarm(context.getContentResolver(), id);
// 資料庫中的時間可能是 0(重複鬧鐘)或明確時間(單次鬧鐘),
// 這裡一併更新,讓 AlarmReceiver 有正確的時間可以比對。
alarm.time = time; // 將時間寫回
enableAlert(context, alarm, time);
return true;
}
最後一哩路是 enableAlert()。它取得 AlarmManager 服務,用 RTC_WAKEUP 計時型鬧鐘搭配自訂的 Action,確保時間一到就能喚醒裝置。
/**
* Sets alert in AlarmManager and StatusBar. This is what will
* actually launch the alert when the alarm triggers.
*
* @param alarm Alarm.
* @param atTimeInMillis milliseconds since epoch
*/
private static void enableAlert(Context context, final Alarm alarm,
final long atTimeInMillis) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ALARM_ALERT_ACTION);
// 接收鬧鐘的廣播意圖,Action 為 "ALARM_ALERT_ACTION"
PendingIntent sender = PendingIntent.getBroadcast(
context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender); // 設定鬧鐘
}
時間到,AlarmReceiver 被喚醒。它做兩件事:把提醒畫面拉到前台,以及啟動服務播放鈴聲與震動。
/**
* Glue class: connects AlarmAlert IntentReceiver to AlarmAlert activity.
* Passes through Alarm ID.
*/
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// launch UI, explicitly stating that this is not due to user action
// so that the current app's notification management is not disturbed
Intent alarmAlert = new Intent(context, AlarmAlert.class);
alarmAlert.putExtra(Alarms.ALARM_INTENT_EXTRA, mAlarm);
alarmAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
context.startActivity(alarmAlert);
// Play the alarm alert and vibrate the device.
Intent playAlarm = new Intent(Alarms.ALARM_ALERT_ACTION);
playAlarm.putExtra(Alarms.ALARM_INTENT_EXTRA, mAlarm);
context.startService(playAlarm);
}
}
整條鏈條串起來就是:AlarmManager 計時 → AlarmReceiver 收訊 → 提醒畫面與服務啟動 → 使用者選擇關閉或貪睡 → Alarms 重寫偏好設定並重新排程。理解這個循環,你就能做出任何自訂提醒類型的應用。
完美的Android手機作業系統:從Eee PC到電視機
Android手機作業系統的設計初衷是智慧型手機平台,但已有數家筆記型電腦與數位相框廠商對它做了嘗試,並進一步探索在自家領域拓展這項業務的可能。 為什麼它能跨出 } A
Android 作業系統的商業價值:陣營成員的算盤與共同焦慮
電信運營商希望透過 Android 加強對終端市場的掌控與限制;手機製造商則普遍看好這套系統,把 Android 列為「多作業系統策略」的必選項,有人甚至視之為「最後的救
Android 2.0 全面解析:新 API、Eclair 與 G1 的三方合作
Android 智慧手機為開發者帶來了一系列新 API,包含同步與藍牙等功能。對開發人員而言,Android 2.0 平台可作為 SDK 的一部分下載,內容涵蓋完整的 A
不是蜂巢!Google 公布 Android 3.0 官方標識是一隻蜜蜂
Android 3.0 Honeycomb(蜂巢)已在 2011 年 CES 上亮相,最終預覽版 SDK 也釋出,稍後的 Google I/O 大會還會重點講解。不過在此