Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 鬧鐘實作全解析:AlarmManager、廣播接收與貪睡機制

編輯:進階開發

想在 Android 上做出一個可靠的鬧鐘,核心其實只有三件事:把鬧鐘登報給系統、讓系統在約定時間主動通知你、以及在通知抵達時決定要做什麼。本文以 Android 內建時鐘的 AlarmAlert 與 Alarms 類別為例,把整個環節拆開來看。

實作三步驟

第一步:註冊鬧鐘。透過 AlarmManager 搭配 PendingIntent 與 Intent,把「幾點要響」這件事交給系統。

第二步:註冊鬧鐘廣播接收者。撰寫一個 BroadcastReceiver,負責接收時間到齊的訊號。

第三步:處理時間到的行為。例如拉開某個應用、跳提示視窗、播放鈴聲或啟動震動,端看你想怎麼提醒使用者。

貪睡(Snooze)流程

鬧鐘響起時,使用者多半只有兩個選擇:關掉,或再睡一會兒。以下程式碼示範了「稍後再響」按鈕的綁定,以及貪睡時間的計算與保存。

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 重寫偏好設定並重新排程。理解這個循環,你就能做出任何自訂提醒類型的應用。

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