CalendarAlarmManager.java revision a7c3f329245dc370151e611fdad85e177f4f6000
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.providers.calendar;
18
19import com.android.providers.calendar.CalendarDatabaseHelper.Tables;
20import com.android.providers.calendar.CalendarDatabaseHelper.Views;
21import com.google.common.annotations.VisibleForTesting;
22
23import android.app.AlarmManager;
24import android.app.PendingIntent;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.database.Cursor;
29import android.database.sqlite.SQLiteDatabase;
30import android.net.Uri;
31import android.os.PowerManager;
32import android.os.PowerManager.WakeLock;
33import android.os.SystemClock;
34import android.provider.CalendarContract;
35import android.provider.CalendarContract.CalendarAlerts;
36import android.provider.CalendarContract.Calendars;
37import android.provider.CalendarContract.Events;
38import android.provider.CalendarContract.Instances;
39import android.provider.CalendarContract.Reminders;
40import android.text.format.DateUtils;
41import android.text.format.Time;
42import android.util.Log;
43
44import java.util.concurrent.atomic.AtomicBoolean;
45
46/**
47 * We are using the CalendarAlertManager to be able to mock the AlarmManager as the AlarmManager
48 * cannot be extended.
49 *
50 * CalendarAlertManager is delegating its calls to the real AlarmService.
51 */
52public class CalendarAlarmManager {
53    protected static final String TAG = "CalendarAlarmManager";
54
55    // SCHEDULE_ALARM_URI runs scheduleNextAlarm(false)
56    // SCHEDULE_ALARM_REMOVE_URI runs scheduleNextAlarm(true)
57    // TODO: use a service to schedule alarms rather than private URI
58    /* package */static final String SCHEDULE_ALARM_PATH = "schedule_alarms";
59    /* package */static final String SCHEDULE_ALARM_REMOVE_PATH = "schedule_alarms_remove";
60    private static final String REMOVE_ALARM_VALUE = "removeAlarms";
61    /* package */static final Uri SCHEDULE_ALARM_REMOVE_URI = Uri.withAppendedPath(
62            CalendarContract.CONTENT_URI, SCHEDULE_ALARM_REMOVE_PATH);
63    /* package */static final Uri SCHEDULE_ALARM_URI = Uri.withAppendedPath(
64            CalendarContract.CONTENT_URI, SCHEDULE_ALARM_PATH);
65
66    static final String INVALID_CALENDARALERTS_SELECTOR =
67    "_id IN (SELECT ca." + CalendarAlerts._ID + " FROM "
68            + Tables.CALENDAR_ALERTS + " AS ca"
69            + " LEFT OUTER JOIN " + Tables.INSTANCES
70            + " USING (" + Instances.EVENT_ID + ","
71            + Instances.BEGIN + "," + Instances.END + ")"
72            + " LEFT OUTER JOIN " + Tables.REMINDERS + " AS r ON"
73            + " (ca." + CalendarAlerts.EVENT_ID + "=r." + Reminders.EVENT_ID
74            + " AND ca." + CalendarAlerts.MINUTES + "=r." + Reminders.MINUTES + ")"
75            + " LEFT OUTER JOIN " + Views.EVENTS + " AS e ON"
76            + " (ca." + CalendarAlerts.EVENT_ID + "=e." + Events._ID + ")"
77            + " WHERE " + Tables.INSTANCES + "." + Instances.BEGIN + " ISNULL"
78            + "   OR ca." + CalendarAlerts.ALARM_TIME + "<?"
79            + "   OR (r." + Reminders.MINUTES + " ISNULL"
80            + "       AND ca." + CalendarAlerts.MINUTES + "<>0)"
81            + "   OR e." + Calendars.VISIBLE + "=0)";
82
83    /**
84     * We search backward in time for event reminders that we may have missed
85     * and schedule them if the event has not yet expired. The amount in the
86     * past to search backwards is controlled by this constant. It should be at
87     * least a few minutes to allow for an event that was recently created on
88     * the web to make its way to the phone. Two hours might seem like overkill,
89     * but it is useful in the case where the user just crossed into a new
90     * timezone and might have just missed an alarm.
91     */
92    private static final long SCHEDULE_ALARM_SLACK = 2 * DateUtils.HOUR_IN_MILLIS;
93    /**
94     * Alarms older than this threshold will be deleted from the CalendarAlerts
95     * table. This should be at least a day because if the timezone is wrong and
96     * the user corrects it we might delete good alarms that appear to be old
97     * because the device time was incorrectly in the future. This threshold
98     * must also be larger than SCHEDULE_ALARM_SLACK. We add the
99     * SCHEDULE_ALARM_SLACK to ensure this. To make it easier to find and debug
100     * problems with missed reminders, set this to something greater than a day.
101     */
102    private static final long CLEAR_OLD_ALARM_THRESHOLD = 7 * DateUtils.DAY_IN_MILLIS
103            + SCHEDULE_ALARM_SLACK;
104    private static final String SCHEDULE_NEXT_ALARM_WAKE_LOCK = "ScheduleNextAlarmWakeLock";
105    protected static final String ACTION_CHECK_NEXT_ALARM =
106            "com.android.providers.calendar.intent.CalendarProvider2";
107    static final int ALARM_CHECK_DELAY_MILLIS = 5000;
108
109    /**
110     * Used for tracking if the next alarm is already scheduled
111     */
112    @VisibleForTesting
113    protected AtomicBoolean mNextAlarmCheckScheduled;
114    /**
115     * Used for synchronization
116     */
117    @VisibleForTesting
118    protected Object mAlarmLock;
119    /**
120     * Used to keep the process from getting killed while scheduling alarms
121     */
122    private WakeLock mScheduleNextAlarmWakeLock;
123
124    @VisibleForTesting
125    protected Context mContext;
126    private AlarmManager mAlarmManager;
127
128    public CalendarAlarmManager(Context context) {
129        initializeWithContext(context);
130    }
131
132    protected void initializeWithContext(Context context) {
133        mContext = context;
134        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
135        mNextAlarmCheckScheduled = new AtomicBoolean(false);
136        mAlarmLock = new Object();
137    }
138
139    void scheduleNextAlarm(boolean removeAlarms) {
140        if (!mNextAlarmCheckScheduled.getAndSet(true)) {
141            if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
142                Log.d(CalendarProvider2.TAG, "Scheduling check of next Alarm");
143            }
144            Intent intent = new Intent(ACTION_CHECK_NEXT_ALARM);
145            intent.putExtra(REMOVE_ALARM_VALUE, removeAlarms);
146            PendingIntent pending = PendingIntent.getBroadcast(mContext, 0 /* ignored */, intent,
147                    PendingIntent.FLAG_NO_CREATE);
148            if (pending != null) {
149                // Cancel any previous Alarm check requests
150                cancel(pending);
151            }
152            pending = PendingIntent.getBroadcast(mContext, 0 /* ignored */, intent,
153                    PendingIntent.FLAG_CANCEL_CURRENT);
154
155            // Trigger the check in 5s from now
156            long triggerAtTime = SystemClock.elapsedRealtime() + ALARM_CHECK_DELAY_MILLIS;
157            set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pending);
158        }
159    }
160
161    PowerManager.WakeLock getScheduleNextAlarmWakeLock() {
162        if (mScheduleNextAlarmWakeLock == null) {
163            PowerManager powerManager = (PowerManager) mContext.getSystemService(
164                    Context.POWER_SERVICE);
165            // Create a wake lock that will be used when we are actually
166            // scheduling the next alarm
167            mScheduleNextAlarmWakeLock = powerManager.newWakeLock(
168                    PowerManager.PARTIAL_WAKE_LOCK, SCHEDULE_NEXT_ALARM_WAKE_LOCK);
169            // We want the Wake Lock to be reference counted (so that we dont
170            // need to take care
171            // about its reference counting)
172            mScheduleNextAlarmWakeLock.setReferenceCounted(true);
173        }
174        return mScheduleNextAlarmWakeLock;
175    }
176
177    void acquireScheduleNextAlarmWakeLock() {
178        getScheduleNextAlarmWakeLock().acquire();
179    }
180
181    void releaseScheduleNextAlarmWakeLock() {
182        getScheduleNextAlarmWakeLock().release();
183    }
184
185    void rescheduleMissedAlarms() {
186        rescheduleMissedAlarms(mContext.getContentResolver());
187    }
188
189    /**
190     * This method runs in a background thread and schedules an alarm for the
191     * next calendar event, if necessary.
192     *
193     * @param db TODO
194     */
195    void runScheduleNextAlarm(boolean removeAlarms, CalendarProvider2 cp2) {
196        SQLiteDatabase db = cp2.mDb;
197        if (db == null) {
198            return;
199        }
200
201        // Reset so that we can accept other schedules of next alarm
202        mNextAlarmCheckScheduled.set(false);
203        db.beginTransaction();
204        try {
205            if (removeAlarms) {
206                removeScheduledAlarmsLocked(db);
207            }
208            scheduleNextAlarmLocked(db, cp2);
209            db.setTransactionSuccessful();
210        } finally {
211            db.endTransaction();
212        }
213    }
214
215    void scheduleNextAlarmCheck(long triggerTime) {
216        Intent intent = new Intent(CalendarReceiver.SCHEDULE);
217        intent.setClass(mContext, CalendarReceiver.class);
218        PendingIntent pending = PendingIntent.getBroadcast(
219                mContext, 0, intent, PendingIntent.FLAG_NO_CREATE);
220        if (pending != null) {
221            // Cancel any previous alarms that do the same thing.
222            cancel(pending);
223        }
224        pending = PendingIntent.getBroadcast(
225                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
226
227        if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
228            Time time = new Time();
229            time.set(triggerTime);
230            String timeStr = time.format(" %a, %b %d, %Y %I:%M%P");
231            Log.d(CalendarProvider2.TAG, "scheduleNextAlarmCheck at: " + triggerTime + timeStr);
232        }
233
234        set(AlarmManager.RTC_WAKEUP, triggerTime, pending);
235    }
236
237    /**
238     * This method looks at the 24-hour window from now for any events that it
239     * needs to schedule. This method runs within a database transaction. It
240     * also runs in a background thread. The CalendarProvider2 keeps track of
241     * which alarms it has already scheduled to avoid scheduling them more than
242     * once and for debugging problems with alarms. It stores this knowledge in
243     * a database table called CalendarAlerts which persists across reboots. But
244     * the actual alarm list is in memory and disappears if the phone loses
245     * power. To avoid missing an alarm, we clear the entries in the
246     * CalendarAlerts table when we start up the CalendarProvider2. Scheduling
247     * an alarm multiple times is not tragic -- we filter out the extra ones
248     * when we receive them. But we still need to keep track of the scheduled
249     * alarms. The main reason is that we need to prevent multiple notifications
250     * for the same alarm (on the receive side) in case we accidentally schedule
251     * the same alarm multiple times. We don't have visibility into the system's
252     * alarm list so we can never know for sure if we have already scheduled an
253     * alarm and it's better to err on scheduling an alarm twice rather than
254     * missing an alarm. Another reason we keep track of scheduled alarms in a
255     * database table is that it makes it easy to run an SQL query to find the
256     * next reminder that we haven't scheduled.
257     *
258     * @param db the database
259     * @param cp2 TODO
260     */
261    private void scheduleNextAlarmLocked(SQLiteDatabase db, CalendarProvider2 cp2) {
262        Time time = new Time();
263
264        final long currentMillis = System.currentTimeMillis();
265        final long start = currentMillis - SCHEDULE_ALARM_SLACK;
266        final long end = start + (24 * 60 * 60 * 1000);
267        if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
268            time.set(start);
269            String startTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
270            Log.d(CalendarProvider2.TAG, "runScheduleNextAlarm() start search: " + startTimeStr);
271        }
272
273        // Delete rows in CalendarAlert where the corresponding Instance or
274        // Reminder no longer exist.
275        // Also clear old alarms but keep alarms around for a while to prevent
276        // multiple alerts for the same reminder. The "clearUpToTime'
277        // should be further in the past than the point in time where
278        // we start searching for events (the "start" variable defined above).
279        String selectArg[] = new String[] { Long.toString(
280                currentMillis - CLEAR_OLD_ALARM_THRESHOLD) };
281
282        int rowsDeleted = db.delete(
283                CalendarAlerts.TABLE_NAME, INVALID_CALENDARALERTS_SELECTOR, selectArg);
284
285        long nextAlarmTime = end;
286        final ContentResolver resolver = mContext.getContentResolver();
287        final long tmpAlarmTime = CalendarAlerts.findNextAlarmTime(resolver, currentMillis);
288        if (tmpAlarmTime != -1 && tmpAlarmTime < nextAlarmTime) {
289            nextAlarmTime = tmpAlarmTime;
290        }
291
292        // Extract events from the database sorted by alarm time. The
293        // alarm times are computed from Instances.begin (whose units
294        // are milliseconds) and Reminders.minutes (whose units are
295        // minutes).
296        //
297        // Also, ignore events whose end time is already in the past.
298        // Also, ignore events alarms that we have already scheduled.
299        //
300        // Note 1: we can add support for the case where Reminders.minutes
301        // equals -1 to mean use Calendars.minutes by adding a UNION for
302        // that case where the two halves restrict the WHERE clause on
303        // Reminders.minutes != -1 and Reminders.minutes = 1, respectively.
304        //
305        // Note 2: we have to name "myAlarmTime" different from the
306        // "alarmTime" column in CalendarAlerts because otherwise the
307        // query won't find multiple alarms for the same event.
308        //
309        // The CAST is needed in the query because otherwise the expression
310        // will be untyped and sqlite3's manifest typing will not convert the
311        // string query parameter to an int in myAlarmtime>=?, so the comparison
312        // will fail. This could be simplified if bug 2464440 is resolved.
313
314        time.setToNow();
315        time.normalize(false);
316        long localOffset = time.gmtoff * 1000;
317
318        String allDayOffset = " -(" + localOffset + ") ";
319        String subQueryPrefix = "SELECT " + Instances.BEGIN;
320        String subQuerySuffix = " -(" + Reminders.MINUTES + "*" + +DateUtils.MINUTE_IN_MILLIS + ")"
321                + " AS myAlarmTime" + "," + Tables.INSTANCES + "." + Instances.EVENT_ID
322                + " AS eventId" + "," + Instances.BEGIN + "," + Instances.END + ","
323                + Instances.TITLE + "," + Instances.ALL_DAY + "," + Reminders.METHOD + ","
324                + Reminders.MINUTES + " FROM " + Tables.INSTANCES + " INNER JOIN " + Views.EVENTS
325                + " ON (" + Views.EVENTS + "." + Events._ID + "=" + Tables.INSTANCES + "."
326                + Instances.EVENT_ID + ")" + " INNER JOIN " + Tables.REMINDERS + " ON ("
327                + Tables.INSTANCES + "." + Instances.EVENT_ID + "=" + Tables.REMINDERS + "."
328                + Reminders.EVENT_ID + ")" + " WHERE " + Calendars.VISIBLE + "=1"
329                + " AND myAlarmTime>=CAST(? AS INT)" + " AND myAlarmTime<=CAST(? AS INT)" + " AND "
330                + Instances.END + ">=?" + " AND " + Reminders.METHOD + "=" + Reminders.METHOD_ALERT;
331
332        // we query separately for all day events to convert to local time from
333        // UTC
334        // we need to /subtract/ the offset to get the correct resulting local
335        // time
336        String allDayQuery = subQueryPrefix + allDayOffset + subQuerySuffix + " AND "
337                + Instances.ALL_DAY + "=1";
338        String nonAllDayQuery = subQueryPrefix + subQuerySuffix + " AND " + Instances.ALL_DAY
339                + "=0";
340
341        // we use UNION ALL because we are guaranteed to have no dupes between
342        // the two queries, and it is less expensive
343        String query = "SELECT *" + " FROM (" + allDayQuery + " UNION ALL " + nonAllDayQuery + ")"
344        // avoid rescheduling existing alarms
345                + " WHERE 0=(SELECT count(*) FROM " + Tables.CALENDAR_ALERTS + " CA" + " WHERE CA."
346                + CalendarAlerts.EVENT_ID + "=eventId" + " AND CA." + CalendarAlerts.BEGIN + "="
347                + Instances.BEGIN + " AND CA." + CalendarAlerts.ALARM_TIME + "=myAlarmTime)"
348                + " ORDER BY myAlarmTime," + Instances.BEGIN + "," + Instances.TITLE;
349
350        String queryParams[] = new String[] { String.valueOf(start), String.valueOf(nextAlarmTime),
351                String.valueOf(currentMillis), String.valueOf(start), String.valueOf(nextAlarmTime),
352                String.valueOf(currentMillis) };
353
354        String instancesTimezone = cp2.mCalendarCache.readTimezoneInstances();
355        boolean isHomeTimezone = cp2.mCalendarCache.readTimezoneType().equals(
356                CalendarCache.TIMEZONE_TYPE_HOME);
357        // expand this range by a day on either end to account for all day
358        // events
359        cp2.acquireInstanceRangeLocked(
360                start - DateUtils.DAY_IN_MILLIS, end + DateUtils.DAY_IN_MILLIS, false /*
361                                                                                       * don't
362                                                                                       * use
363                                                                                       * minimum
364                                                                                       * expansion
365                                                                                       * windows
366                                                                                       */,
367                false /* do not force Instances deletion and expansion */, instancesTimezone,
368                isHomeTimezone);
369        Cursor cursor = null;
370        try {
371            cursor = db.rawQuery(query, queryParams);
372
373            final int beginIndex = cursor.getColumnIndex(Instances.BEGIN);
374            final int endIndex = cursor.getColumnIndex(Instances.END);
375            final int eventIdIndex = cursor.getColumnIndex("eventId");
376            final int alarmTimeIndex = cursor.getColumnIndex("myAlarmTime");
377            final int minutesIndex = cursor.getColumnIndex(Reminders.MINUTES);
378
379            if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
380                time.set(nextAlarmTime);
381                String alarmTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
382                Log.d(CalendarProvider2.TAG,
383                        "cursor results: " + cursor.getCount() + " nextAlarmTime: " + alarmTimeStr);
384            }
385
386            while (cursor.moveToNext()) {
387                // Schedule all alarms whose alarm time is as early as any
388                // scheduled alarm. For example, if the earliest alarm is at
389                // 1pm, then we will schedule all alarms that occur at 1pm
390                // but no alarms that occur later than 1pm.
391                // Actually, we allow alarms up to a minute later to also
392                // be scheduled so that we don't have to check immediately
393                // again after an event alarm goes off.
394                final long alarmTime = cursor.getLong(alarmTimeIndex);
395                final long eventId = cursor.getLong(eventIdIndex);
396                final int minutes = cursor.getInt(minutesIndex);
397                final long startTime = cursor.getLong(beginIndex);
398                final long endTime = cursor.getLong(endIndex);
399
400                if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
401                    time.set(alarmTime);
402                    String schedTime = time.format(" %a, %b %d, %Y %I:%M%P");
403                    time.set(startTime);
404                    String startTimeStr = time.format(" %a, %b %d, %Y %I:%M%P");
405
406                    Log.d(CalendarProvider2.TAG,
407                            "  looking at id: " + eventId + " " + startTime + startTimeStr
408                                    + " alarm: " + alarmTime + schedTime);
409                }
410
411                if (alarmTime < nextAlarmTime) {
412                    nextAlarmTime = alarmTime;
413                } else if (alarmTime > nextAlarmTime + DateUtils.MINUTE_IN_MILLIS) {
414                    // This event alarm (and all later ones) will be scheduled
415                    // later.
416                    if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
417                        Log.d(CalendarProvider2.TAG,
418                                "This event alarm (and all later ones) will be scheduled later");
419                    }
420                    break;
421                }
422
423                // Avoid an SQLiteContraintException by checking if this alarm
424                // already exists in the table.
425                if (CalendarAlerts.alarmExists(resolver, eventId, startTime, alarmTime)) {
426                    if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
427                        int titleIndex = cursor.getColumnIndex(Events.TITLE);
428                        String title = cursor.getString(titleIndex);
429                        Log.d(CalendarProvider2.TAG,
430                                "  alarm exists for id: " + eventId + " " + title);
431                    }
432                    continue;
433                }
434
435                // Insert this alarm into the CalendarAlerts table
436                Uri uri = CalendarAlerts.insert(
437                        resolver, eventId, startTime, endTime, alarmTime, minutes);
438                if (uri == null) {
439                    if (Log.isLoggable(CalendarProvider2.TAG, Log.ERROR)) {
440                        Log.e(CalendarProvider2.TAG, "runScheduleNextAlarm() insert into "
441                                + "CalendarAlerts table failed");
442                    }
443                    continue;
444                }
445
446                scheduleAlarm(alarmTime);
447            }
448        } finally {
449            if (cursor != null) {
450                cursor.close();
451            }
452        }
453
454        // Refresh notification bar
455        if (rowsDeleted > 0) {
456            scheduleAlarm(currentMillis);
457        }
458
459        // If we scheduled an event alarm, then schedule the next alarm check
460        // for one minute past that alarm. Otherwise, if there were no
461        // event alarms scheduled, then check again in 24 hours. If a new
462        // event is inserted before the next alarm check, then this method
463        // will be run again when the new event is inserted.
464        if (nextAlarmTime != Long.MAX_VALUE) {
465            scheduleNextAlarmCheck(nextAlarmTime + DateUtils.MINUTE_IN_MILLIS);
466        } else {
467            scheduleNextAlarmCheck(currentMillis + DateUtils.DAY_IN_MILLIS);
468        }
469    }
470
471    /**
472     * Removes the entries in the CalendarAlerts table for alarms that we have
473     * scheduled but that have not fired yet. We do this to ensure that we don't
474     * miss an alarm. The CalendarAlerts table keeps track of the alarms that we
475     * have scheduled but the actual alarm list is in memory and will be cleared
476     * if the phone reboots. We don't need to remove entries that have already
477     * fired, and in fact we should not remove them because we need to display
478     * the notifications until the user dismisses them. We could remove entries
479     * that have fired and been dismissed, but we leave them around for a while
480     * because it makes it easier to debug problems. Entries that are old enough
481     * will be cleaned up later when we schedule new alarms.
482     */
483    private static void removeScheduledAlarmsLocked(SQLiteDatabase db) {
484        if (Log.isLoggable(CalendarProvider2.TAG, Log.DEBUG)) {
485            Log.d(CalendarProvider2.TAG, "removing scheduled alarms");
486        }
487        db.delete(CalendarAlerts.TABLE_NAME, CalendarAlerts.STATE + "="
488                + CalendarAlerts.STATE_SCHEDULED, null /* whereArgs */);
489    }
490
491    public void set(int type, long triggerAtTime, PendingIntent operation) {
492        mAlarmManager.set(type, triggerAtTime, operation);
493    }
494
495    public void cancel(PendingIntent operation) {
496        mAlarmManager.cancel(operation);
497    }
498
499    public void scheduleAlarm(long alarmTime) {
500        CalendarContract.CalendarAlerts.scheduleAlarm(mContext, mAlarmManager, alarmTime);
501    }
502
503    public void rescheduleMissedAlarms(ContentResolver cr) {
504        CalendarContract.CalendarAlerts.rescheduleMissedAlarms(cr, mContext, mAlarmManager);
505    }
506}
507