AlertService.java revision 62d3b564f193615395617fd193b6b8487ba8cf0f
1/*
2 * Copyright (C) 2008 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.calendar.alerts;
18
19import com.android.calendar.GeneralPreferences;
20import com.android.calendar.R;
21import com.android.calendar.Utils;
22
23import android.app.AlarmManager;
24import android.app.Notification;
25import android.app.NotificationManager;
26import android.app.Service;
27import android.content.ContentResolver;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
32import android.content.SharedPreferences;
33import android.database.Cursor;
34import android.media.AudioManager;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.HandlerThread;
39import android.os.IBinder;
40import android.os.Looper;
41import android.os.Message;
42import android.os.Process;
43import android.provider.CalendarContract;
44import android.provider.CalendarContract.Attendees;
45import android.provider.CalendarContract.CalendarAlerts;
46import android.text.TextUtils;
47import android.text.format.DateUtils;
48import android.text.format.Time;
49import android.util.Log;
50
51import java.util.ArrayList;
52import java.util.HashMap;
53import java.util.List;
54
55/**
56 * This service is used to handle calendar event reminders.
57 */
58public class AlertService extends Service {
59    static final boolean DEBUG = true;
60    private static final String TAG = "AlertService";
61
62    private volatile Looper mServiceLooper;
63    private volatile ServiceHandler mServiceHandler;
64
65    private static final String[] ALERT_PROJECTION = new String[] {
66        CalendarAlerts._ID,                     // 0
67        CalendarAlerts.EVENT_ID,                // 1
68        CalendarAlerts.STATE,                   // 2
69        CalendarAlerts.TITLE,                   // 3
70        CalendarAlerts.EVENT_LOCATION,          // 4
71        CalendarAlerts.SELF_ATTENDEE_STATUS,    // 5
72        CalendarAlerts.ALL_DAY,                 // 6
73        CalendarAlerts.ALARM_TIME,              // 7
74        CalendarAlerts.MINUTES,                 // 8
75        CalendarAlerts.BEGIN,                   // 9
76        CalendarAlerts.END,                     // 10
77        CalendarAlerts.DESCRIPTION,             // 11
78    };
79
80    private static final int ALERT_INDEX_ID = 0;
81    private static final int ALERT_INDEX_EVENT_ID = 1;
82    private static final int ALERT_INDEX_STATE = 2;
83    private static final int ALERT_INDEX_TITLE = 3;
84    private static final int ALERT_INDEX_EVENT_LOCATION = 4;
85    private static final int ALERT_INDEX_SELF_ATTENDEE_STATUS = 5;
86    private static final int ALERT_INDEX_ALL_DAY = 6;
87    private static final int ALERT_INDEX_ALARM_TIME = 7;
88    private static final int ALERT_INDEX_MINUTES = 8;
89    private static final int ALERT_INDEX_BEGIN = 9;
90    private static final int ALERT_INDEX_END = 10;
91    private static final int ALERT_INDEX_DESCRIPTION = 11;
92
93    private static final String ACTIVE_ALERTS_SELECTION = "(" + CalendarAlerts.STATE + "=? OR "
94            + CalendarAlerts.STATE + "=?) AND " + CalendarAlerts.ALARM_TIME + "<=";
95
96    private static final String[] ACTIVE_ALERTS_SELECTION_ARGS = new String[] {
97            Integer.toString(CalendarAlerts.STATE_FIRED),
98            Integer.toString(CalendarAlerts.STATE_SCHEDULED)
99    };
100
101    private static final String ACTIVE_ALERTS_SORT = "begin DESC, end DESC";
102
103    private static final String DISMISS_OLD_SELECTION = CalendarAlerts.END + "<? AND "
104            + CalendarAlerts.STATE + "=?";
105
106    private static final int MINUTE_MS = 60 * 1000;
107
108    // The grace period before changing a notification's priority bucket.
109    private static final int MIN_DEPRIORITIZE_GRACE_PERIOD_MS = 15 * MINUTE_MS;
110
111    // Hard limit to the number of notifications displayed.
112    private static final int MAX_NOTIFICATIONS = 20;
113
114    void processMessage(Message msg) {
115        Bundle bundle = (Bundle) msg.obj;
116
117        // On reboot, update the notification bar with the contents of the
118        // CalendarAlerts table.
119        String action = bundle.getString("action");
120        if (DEBUG) {
121            Log.d(TAG, bundle.getLong(android.provider.CalendarContract.CalendarAlerts.ALARM_TIME)
122                    + " Action = " + action);
123        }
124
125        if (action.equals(Intent.ACTION_BOOT_COMPLETED)
126                || action.equals(Intent.ACTION_TIME_CHANGED)) {
127            doTimeChanged();
128            return;
129        }
130
131        if (!action.equals(android.provider.CalendarContract.ACTION_EVENT_REMINDER)
132                && !action.equals(Intent.ACTION_LOCALE_CHANGED)
133                && !action.equals(AlertReceiver.ACTION_DISMISS_OLD_REMINDERS)) {
134            Log.w(TAG, "Invalid action: " + action);
135            return;
136        }
137        if (action.equals(AlertReceiver.ACTION_DISMISS_OLD_REMINDERS)) {
138            dismissOldAlerts(this);
139        }
140
141        if (action.equals(android.provider.CalendarContract.ACTION_EVENT_REMINDER)) {
142            updateAlertNotification(this);
143        }
144    }
145
146    static void dismissOldAlerts(Context context) {
147        ContentResolver cr = context.getContentResolver();
148        final long currentTime = System.currentTimeMillis();
149        ContentValues vals = new ContentValues();
150        vals.put(CalendarAlerts.STATE, CalendarAlerts.STATE_DISMISSED);
151        cr.update(CalendarAlerts.CONTENT_URI, vals, DISMISS_OLD_SELECTION, new String[] {
152                Long.toString(currentTime), Integer.toString(CalendarAlerts.STATE_SCHEDULED)
153        });
154    }
155
156    static boolean updateAlertNotification(Context context) {
157        ContentResolver cr = context.getContentResolver();
158        NotificationManager nm =
159                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
160        final long currentTime = System.currentTimeMillis();
161        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
162
163        if (DEBUG) {
164            Log.d(TAG, "Beginning updateAlertNotification");
165        }
166
167        if (!prefs.getBoolean(GeneralPreferences.KEY_ALERTS, true)) {
168            if (DEBUG) {
169                Log.d(TAG, "alert preference is OFF");
170            }
171
172            // If we shouldn't be showing notifications cancel any existing ones
173            // and return.
174            nm.cancelAll();
175            return true;
176        }
177
178        Cursor alertCursor = cr.query(CalendarAlerts.CONTENT_URI, ALERT_PROJECTION,
179                (ACTIVE_ALERTS_SELECTION + currentTime), ACTIVE_ALERTS_SELECTION_ARGS,
180                ACTIVE_ALERTS_SORT);
181
182        if (alertCursor == null || alertCursor.getCount() == 0) {
183            if (alertCursor != null) {
184                alertCursor.close();
185            }
186
187            if (DEBUG) Log.d(TAG, "No fired or scheduled alerts");
188            nm.cancelAll();
189            return false;
190        }
191
192        if (DEBUG) {
193            Log.d(TAG, "alertCursor count:" + alertCursor.getCount());
194        }
195
196        // Process the query results and bucketize events.
197        ArrayList<NotificationInfo> highPriorityEvents = new ArrayList<NotificationInfo>();
198        ArrayList<NotificationInfo> mediumPriorityEvents = new ArrayList<NotificationInfo>();
199        ArrayList<NotificationInfo> lowPriorityEvents = new ArrayList<NotificationInfo>();
200        int numFired = processQuery(alertCursor, context, currentTime, highPriorityEvents,
201                mediumPriorityEvents, lowPriorityEvents);
202
203        if (highPriorityEvents.size() + mediumPriorityEvents.size()
204                + lowPriorityEvents.size() == 0) {
205            nm.cancelAll();
206            return true;
207        }
208
209        boolean quietUpdate = (numFired == 0);
210        long nextRefreshTime = Long.MAX_VALUE;
211        int currentNotificationId = 1;
212        NotificationPrefs notificationPrefs = new NotificationPrefs(context, prefs, quietUpdate);
213
214        // If there are more high/medium priority events than we can show, bump some to
215        // the low priority digest.
216        redistributeBuckets(highPriorityEvents, mediumPriorityEvents, lowPriorityEvents,
217                MAX_NOTIFICATIONS);
218
219        // Post the individual higher priority events (future and recently started
220        // concurrent events).  Order these so that earlier start times appear higher in
221        // the notification list.
222        for (int i = 0; i < highPriorityEvents.size(); i++) {
223            NotificationInfo info = highPriorityEvents.get(i);
224            String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis,
225                    info.allDay, info.location);
226            postNotification(info, summaryText, context, true, notificationPrefs, nm,
227                    currentNotificationId++);
228
229            // Keep concurrent events high priority (to appear higher in the notification list)
230            // until 15 minutes into the event.
231            nextRefreshTime = Math.min(nextRefreshTime, getNextRefreshTime(info, currentTime));
232        }
233
234        // Post the medium priority events (concurrent events that started a while ago).
235        // Order these so more recent start times appear higher in the notification list.
236        //
237        // TODO: Post these with the same notification priority level as the higher priority
238        // events, so that all notifications will be co-located together.
239        for (int i = mediumPriorityEvents.size() - 1; i >= 0; i--) {
240            NotificationInfo info = mediumPriorityEvents.get(i);
241            // TODO: Change to a relative time description like: "Started 40 minutes ago".
242            // This requires constant refreshing to the message as time goes.
243            String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis,
244                    info.allDay, info.location);
245            postNotification(info, summaryText, context, false, notificationPrefs, nm,
246                    currentNotificationId++);
247
248            // Refresh when concurrent event ends so it will drop into the expired digest.
249            nextRefreshTime = Math.min(nextRefreshTime, getNextRefreshTime(info, currentTime));
250        }
251
252        // Post the low priority events as 1 combined notification.
253        int numLowPriority = lowPriorityEvents.size();
254        if (numLowPriority > 0) {
255            String expiredDigestTitle = getDigestTitle(lowPriorityEvents);
256            Notification notification;
257            if (numLowPriority == 1) {
258                // If only 1 expired event, display an "old-style" basic alert.
259                NotificationInfo info = lowPriorityEvents.get(0);
260                String summaryText = AlertUtils.formatTimeLocation(context, info.startMillis,
261                        info.allDay, info.location);
262                notification = AlertReceiver.makeBasicNotification(context, info.eventName,
263                        summaryText, info.startMillis, info.endMillis, info.eventId,
264                        AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, false);
265            } else {
266                // Multiple expired events are listed in a digest.
267                notification = AlertReceiver.makeDigestNotification(context,
268                    lowPriorityEvents, expiredDigestTitle, false);
269            }
270
271            // Add options for a quiet update.
272            addNotificationOptions(notification, true, expiredDigestTitle,
273                    notificationPrefs.getDefaultVibrate(),
274                    notificationPrefs.getRingtoneAndSilence());
275
276            // Post the new notification for the group.
277            nm.notify(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, notification);
278
279            if (DEBUG) {
280                Log.d(TAG, "Quietly posting digest alarm notification, numEvents:" + numLowPriority
281                        + ", notificationId:" + AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
282            }
283        } else {
284            nm.cancel(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
285            if (DEBUG) {
286                Log.d(TAG, "No low priority events, canceling the digest notification.");
287            }
288        }
289
290        // Remove the notifications that are hanging around from the previous refresh.
291        if (currentNotificationId <= MAX_NOTIFICATIONS) {
292            for (int i = currentNotificationId; i <= MAX_NOTIFICATIONS; i++) {
293                nm.cancel(i);
294            }
295            if (DEBUG) {
296                Log.d(TAG, "Canceling leftover notification IDs " + currentNotificationId + "-"
297                        + MAX_NOTIFICATIONS);
298            }
299        }
300
301        // Schedule the next silent refresh time so notifications will change
302        // buckets (eg. drop into expired digest, etc).
303        if (nextRefreshTime < Long.MAX_VALUE && nextRefreshTime > currentTime) {
304            AlertUtils.scheduleNextNotificationRefresh(context, null, nextRefreshTime);
305            if (DEBUG) {
306                long minutesBeforeRefresh = (nextRefreshTime - currentTime) / MINUTE_MS;
307                Time time = new Time();
308                time.set(nextRefreshTime);
309                String msg = String.format("Scheduling next notification refresh in %d min at: "
310                        + "%d:%02d", minutesBeforeRefresh, time.hour, time.minute);
311                Log.d(TAG, msg);
312            }
313        } else if (nextRefreshTime < currentTime) {
314            Log.e(TAG, "Illegal state: next notification refresh time found to be in the past.");
315        }
316
317        return true;
318    }
319
320    /**
321     * Redistributes events in the priority lists based on the max # of notifications we
322     * can show.
323     */
324    static void redistributeBuckets(ArrayList<NotificationInfo> highPriorityEvents,
325            ArrayList<NotificationInfo> mediumPriorityEvents,
326            ArrayList<NotificationInfo> lowPriorityEvents, int maxNotifications) {
327
328        // If too many high priority alerts, shift the remaining high priority and all the
329        // medium priority ones to the low priority bucket.  Note that order is important
330        // here; these lists are sorted by descending start time.  Maintain that ordering
331        // so posted notifications are in the expected order.
332        if (highPriorityEvents.size() > maxNotifications) {
333            // Move mid-priority to the digest.
334            lowPriorityEvents.addAll(0, mediumPriorityEvents);
335
336            // Move the rest of the high priority ones (latest ones) to the digest.
337            List<NotificationInfo> itemsToMoveSublist = highPriorityEvents.subList(
338                    0, highPriorityEvents.size() - maxNotifications);
339            // TODO: What order for high priority in the digest?
340            lowPriorityEvents.addAll(0, itemsToMoveSublist);
341            if (DEBUG) {
342                logEventIdsBumped(mediumPriorityEvents, itemsToMoveSublist);
343            }
344            mediumPriorityEvents.clear();
345            // Clearing the sublist view removes the items from the highPriorityEvents list.
346            itemsToMoveSublist.clear();
347        }
348
349        // Bump the medium priority events if necessary.
350        if (mediumPriorityEvents.size() + highPriorityEvents.size() > maxNotifications) {
351            int spaceRemaining = maxNotifications - highPriorityEvents.size();
352
353            // Reached our max, move the rest to the digest.
354            List<NotificationInfo> itemsToMoveSublist = mediumPriorityEvents.subList(
355                    spaceRemaining, mediumPriorityEvents.size());
356            lowPriorityEvents.addAll(0, itemsToMoveSublist);
357            if (DEBUG) {
358                logEventIdsBumped(itemsToMoveSublist, null);
359            }
360
361            // Clearing the sublist view removes the items from the mediumPriorityEvents list.
362            itemsToMoveSublist.clear();
363        }
364    }
365
366    private static void logEventIdsBumped(List<NotificationInfo> list1,
367            List<NotificationInfo> list2) {
368        StringBuilder ids = new StringBuilder();
369        if (list1 != null) {
370            for (NotificationInfo info : list1) {
371                ids.append(info.eventId);
372                ids.append(",");
373            }
374        }
375        if (list2 != null) {
376            for (NotificationInfo info : list2) {
377                ids.append(info.eventId);
378                ids.append(",");
379            }
380        }
381        if (ids.length() > 0 && ids.charAt(ids.length() - 1) == ',') {
382            ids.setLength(ids.length() - 1);
383        }
384        if (ids.length() > 0) {
385            Log.d(TAG, "Reached max postings, bumping event IDs {" + ids.toString()
386                    + "} to digest.");
387        }
388    }
389
390    private static long getNextRefreshTime(NotificationInfo info, long currentTime) {
391        // We change an event's priority bucket at 15 minutes into the event (so recently started
392        // concurrent events stay high priority)
393        long nextRefreshTime = Long.MAX_VALUE;
394        long gracePeriodCutoff = info.startMillis +
395                getGracePeriodMs(info.startMillis, info.endMillis);
396        if (gracePeriodCutoff > currentTime) {
397            nextRefreshTime = Math.min(nextRefreshTime, gracePeriodCutoff);
398        }
399
400        // ... and at the end (so expiring ones drop into a digest).
401        if (info.endMillis > currentTime && info.endMillis > gracePeriodCutoff) {
402            nextRefreshTime = Math.min(nextRefreshTime, info.endMillis);
403        }
404        return nextRefreshTime;
405    }
406
407    /**
408     * Processes the query results and bucketizes the alerts.
409     *
410     * @param highPriorityEvents This will contain future events, and concurrent events
411     *     that started recently (less than the interval DEPRIORITIZE_GRACE_PERIOD_MS).
412     * @param mediumPriorityEvents This will contain concurrent events that started
413     *     more than DEPRIORITIZE_GRACE_PERIOD_MS ago.
414     * @param lowPriorityEvents Will contain events that have ended.
415     * @return Returns the number of new alerts to fire.  If this is 0, it implies
416     *     a quiet update.
417     */
418    private static int processQuery(final Cursor alertCursor, final Context context,
419            final long currentTime, ArrayList<NotificationInfo> highPriorityEvents,
420            ArrayList<NotificationInfo> mediumPriorityEvents,
421            ArrayList<NotificationInfo> lowPriorityEvents) {
422        ContentResolver cr = context.getContentResolver();
423        HashMap<Long, NotificationInfo> eventIds = new HashMap<Long, NotificationInfo>();
424        int numFired = 0;
425        int notificationId = 1;
426        try {
427            while (alertCursor.moveToNext()) {
428                final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
429                final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
430                final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
431                final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
432                final String description = alertCursor.getString(ALERT_INDEX_DESCRIPTION);
433                final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
434                final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS);
435                final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED;
436                final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
437                final long endTime = alertCursor.getLong(ALERT_INDEX_END);
438                final Uri alertUri = ContentUris
439                        .withAppendedId(CalendarAlerts.CONTENT_URI, alertId);
440                final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
441                int state = alertCursor.getInt(ALERT_INDEX_STATE);
442                final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
443
444                if (DEBUG) {
445                    Log.d(TAG, "alertCursor result: alarmTime:" + alarmTime + " alertId:" + alertId
446                            + " eventId:" + eventId + " state: " + state + " minutes:" + minutes
447                            + " declined:" + declined + " beginTime:" + beginTime
448                            + " endTime:" + endTime + " allDay:" + allDay);
449                }
450
451                ContentValues values = new ContentValues();
452                int newState = -1;
453                boolean newAlert = false;
454
455                // Uncomment for the behavior of clearing out alerts after the
456                // events ended. b/1880369
457                //
458                // if (endTime < currentTime) {
459                //     newState = CalendarAlerts.DISMISSED;
460                // } else
461
462                // Remove declined events
463                if (!declined) {
464                    if (state == CalendarAlerts.STATE_SCHEDULED) {
465                        newState = CalendarAlerts.STATE_FIRED;
466                        numFired++;
467                        newAlert = true;
468
469                        // Record the received time in the CalendarAlerts table.
470                        // This is useful for finding bugs that cause alarms to be
471                        // missed or delayed.
472                        values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
473                    }
474                } else {
475                    newState = CalendarAlerts.STATE_DISMISSED;
476                }
477
478                // Update row if state changed
479                if (newState != -1) {
480                    values.put(CalendarAlerts.STATE, newState);
481                    state = newState;
482                }
483
484                if (state == CalendarAlerts.STATE_FIRED) {
485                    // Record the time posting to notification manager.
486                    // This is used for debugging missed alarms.
487                    values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
488                }
489
490                // Write row to if anything changed
491                if (values.size() > 0) cr.update(alertUri, values, null, null);
492
493                if (state != CalendarAlerts.STATE_FIRED) {
494                    continue;
495                }
496
497                // Pick an Event title for the notification panel by the latest
498                // alertTime and give prefer accepted events in case of ties.
499                int newStatus;
500                switch (status) {
501                    case Attendees.ATTENDEE_STATUS_ACCEPTED:
502                        newStatus = 2;
503                        break;
504                    case Attendees.ATTENDEE_STATUS_TENTATIVE:
505                        newStatus = 1;
506                        break;
507                    default:
508                        newStatus = 0;
509                }
510
511                NotificationInfo newInfo = new NotificationInfo(eventName, location,
512                        description, beginTime, endTime, eventId, allDay, newAlert);
513                if (eventIds.containsKey(eventId)) {
514                    NotificationInfo oldInfo = eventIds.get(eventId);
515
516                    // Determine whether to replace the previous reminder with this one.
517                    // Query results are sorted so this one will always have a lower start time.
518                    long oldStartInterval = oldInfo.startMillis - currentTime;
519                    long newStartInterval = newInfo.startMillis - currentTime;
520                    boolean dropOld;
521                    if (newStartInterval < 0 && oldStartInterval > 0) {
522                        // Use this reminder if this event started recently
523                        dropOld = Math.abs(newStartInterval) < MIN_DEPRIORITIZE_GRACE_PERIOD_MS;
524                    } else {
525                        // ... or if this one has a closer start time.
526                        dropOld = Math.abs(newStartInterval) < Math.abs(oldStartInterval);
527                    }
528
529                    if (dropOld) {
530                        // This is a recurring event that has a more relevant start time,
531                        // drop other reminder in favor of this one.
532                        //
533                        // It will only be present in 1 of these buckets; just remove from
534                        // multiple buckets since this occurrence is rare enough that the
535                        // inefficiency of multiple removals shouldn't be a big deal to
536                        // justify a more complicated data structure.  Expired events don't
537                        // have individual notifications so we don't need to clean that up.
538                        highPriorityEvents.remove(oldInfo);
539                        mediumPriorityEvents.remove(oldInfo);
540                        if (DEBUG) {
541                            Log.d(TAG, "Dropping alert for recurring event ID:" + oldInfo.eventId
542                                    + ", startTime:" + oldInfo.startMillis
543                                    + " in favor of startTime:" + newInfo.startMillis);
544                        }
545                    } else {
546                        // Skip duplicate reminders for the same event instance.
547                        continue;
548                    }
549                }
550
551                // Adjust for all day events to ensure the right bucket.  Don't use the 1/4 event
552                // duration grace period for these.
553                long gracePeriodMs;
554                long beginTimeAdjustedForAllDay = beginTime;
555                if (allDay) {
556                    beginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, beginTime,
557                            Utils.getTimeZone(context, null));
558                    gracePeriodMs = MIN_DEPRIORITIZE_GRACE_PERIOD_MS;
559                } else {
560                    gracePeriodMs = getGracePeriodMs(beginTime, endTime);
561                }
562
563                // TODO: Prioritize by "primary" calendar
564                eventIds.put(eventId, newInfo);
565                long highPriorityCutoff = currentTime - gracePeriodMs;
566                if (beginTimeAdjustedForAllDay > highPriorityCutoff) {
567                    // High priority = future events or events that just started
568                    highPriorityEvents.add(newInfo);
569                } else if (allDay && DateUtils.isToday(beginTimeAdjustedForAllDay)) {
570                    // Medium priority = in progress all day events
571                    mediumPriorityEvents.add(newInfo);
572                } else {
573                    lowPriorityEvents.add(newInfo);
574                }
575            }
576        } finally {
577            if (alertCursor != null) {
578                alertCursor.close();
579            }
580        }
581        return numFired;
582    }
583
584    /**
585     * High priority cutoff should be 1/4 event duration or 15 min, whichever is longer.
586     */
587    private static long getGracePeriodMs(long beginTime, long endTime) {
588        return Math.max(MIN_DEPRIORITIZE_GRACE_PERIOD_MS, ((endTime - beginTime) / 4));
589    }
590
591    private static String getDigestTitle(ArrayList<NotificationInfo> events) {
592        StringBuilder digestTitle = new StringBuilder();
593        for (NotificationInfo eventInfo : events) {
594            if (!TextUtils.isEmpty(eventInfo.eventName)) {
595                if (digestTitle.length() > 0) {
596                    digestTitle.append(", ");
597                }
598                digestTitle.append(eventInfo.eventName);
599            }
600        }
601        return digestTitle.toString();
602    }
603
604    private static void postNotification(NotificationInfo info, String summaryText,
605            Context context, boolean highPriority, NotificationPrefs prefs,
606            NotificationManager notificationMgr, int notificationId) {
607        String tickerText = getTickerText(info.eventName, info.location);
608        Notification notification = AlertReceiver.makeExpandingNotification(context,
609                info.eventName, summaryText, info.description, info.startMillis,
610                info.endMillis, info.eventId, notificationId, prefs.getDoPopup(),
611                highPriority);
612
613        boolean quietUpdate = true;
614        String ringtone = NotificationPrefs.EMPTY_RINGTONE;
615        if (info.newAlert) {
616            quietUpdate = prefs.quietUpdate;
617
618            // If we've already played a ringtone, don't play any more sounds so only
619            // 1 sound per group of notifications.
620            ringtone = prefs.getRingtoneAndSilence();
621        }
622        addNotificationOptions(notification, quietUpdate, tickerText,
623                prefs.getDefaultVibrate(), ringtone);
624
625        // Post the notification.
626        notificationMgr.notify(notificationId, notification);
627
628        if (DEBUG) {
629            Log.d(TAG, "Posting individual alarm notification, eventId:" + info.eventId
630                    + ", notificationId:" + notificationId
631                    + (TextUtils.isEmpty(ringtone) ? ", quiet" : ", LOUD")
632                    + (highPriority ? ", high-priority" : ""));
633        }
634    }
635
636    private static String getTickerText(String eventName, String location) {
637        String tickerText = eventName;
638        if (!TextUtils.isEmpty(location)) {
639            tickerText = eventName + " - " + location;
640        }
641        return tickerText;
642    }
643
644    static class NotificationInfo {
645        String eventName;
646        String location;
647        String description;
648        long startMillis;
649        long endMillis;
650        long eventId;
651        boolean allDay;
652        boolean newAlert;
653
654        NotificationInfo(String eventName, String location, String description, long startMillis,
655                long endMillis, long eventId, boolean allDay, boolean newAlert) {
656            this.eventName = eventName;
657            this.location = location;
658            this.description = description;
659            this.startMillis = startMillis;
660            this.endMillis = endMillis;
661            this.eventId = eventId;
662            this.newAlert = newAlert;
663            this.allDay = allDay;
664        }
665    }
666
667    private static void addNotificationOptions(Notification notification, boolean quietUpdate,
668            String tickerText, boolean defaultVibrate, String reminderRingtone) {
669        notification.defaults |= Notification.DEFAULT_LIGHTS;
670
671        // Quietly update notification bar. Nothing new. Maybe something just got deleted.
672        if (!quietUpdate) {
673            // Flash ticker in status bar
674            if (!TextUtils.isEmpty(tickerText)) {
675                notification.tickerText = tickerText;
676            }
677
678            // Generate either a pop-up dialog, status bar notification, or
679            // neither. Pop-up dialog and status bar notification may include a
680            // sound, an alert, or both. A status bar notification also includes
681            // a toast.
682            if (defaultVibrate) {
683                notification.defaults |= Notification.DEFAULT_VIBRATE;
684            }
685
686            // Possibly generate a sound. If 'Silent' is chosen, the ringtone
687            // string will be empty.
688            notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
689                    .parse(reminderRingtone);
690        }
691    }
692
693    private static class NotificationPrefs {
694        boolean quietUpdate;
695        private Context context;
696        private SharedPreferences prefs;
697
698        // These are lazily initialized, do not access any of the following directly; use getters.
699        private int doPopup = -1;
700        private int defaultVibrate = -1;
701        private String ringtone = null;
702
703        private static final String EMPTY_RINGTONE = "";
704
705        NotificationPrefs(Context context, SharedPreferences prefs,
706                boolean quietUpdate) {
707            this.context = context;
708            this.prefs = prefs;
709            this.quietUpdate = quietUpdate;
710        }
711
712        private boolean getDoPopup() {
713            if (doPopup < 0) {
714                if (prefs.getBoolean(GeneralPreferences.KEY_ALERTS_POPUP, false)) {
715                    doPopup = 1;
716                } else {
717                    doPopup = 0;
718                }
719            }
720            return doPopup == 1;
721        }
722
723        private boolean getDefaultVibrate() {
724            if (defaultVibrate < 0) {
725                // Find out the circumstances under which to vibrate.
726                // Migrate from pre-Froyo boolean setting if necessary.
727                String vibrateWhen; // "always" or "silent" or "never"
728                if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN))
729                {
730                    // Look up Froyo setting
731                    vibrateWhen =
732                        prefs.getString(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN, null);
733                } else if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE)) {
734                    // No Froyo setting. Migrate pre-Froyo setting to new Froyo-defined value.
735                    boolean vibrate =
736                        prefs.getBoolean(GeneralPreferences.KEY_ALERTS_VIBRATE, false);
737                    vibrateWhen = vibrate ?
738                        context.getString(R.string.prefDefault_alerts_vibrate_true) :
739                        context.getString(R.string.prefDefault_alerts_vibrate_false);
740                } else {
741                    // No setting. Use Froyo-defined default.
742                    vibrateWhen = context.getString(R.string.prefDefault_alerts_vibrateWhen);
743                }
744
745                if (vibrateWhen.equals("always")) {
746                    return true;
747                }
748                if (!vibrateWhen.equals("silent")) {
749                    return false;
750                }
751
752                // Settings are to vibrate when silent.  Return true if it is now silent.
753                AudioManager audioManager =
754                    (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
755                if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
756                    defaultVibrate = 1;
757                } else {
758                    defaultVibrate = 0;
759                }
760            }
761            return defaultVibrate == 1;
762        }
763
764        private String getRingtoneAndSilence() {
765            if (ringtone == null) {
766                if (quietUpdate) {
767                    ringtone = EMPTY_RINGTONE;
768                } else {
769                    ringtone = prefs.getString(GeneralPreferences.KEY_ALERTS_RINGTONE, null);
770                }
771            }
772            String retVal = ringtone;
773            ringtone = EMPTY_RINGTONE;
774            return retVal;
775        }
776    }
777
778    private void doTimeChanged() {
779        ContentResolver cr = getContentResolver();
780        Object service = getSystemService(Context.ALARM_SERVICE);
781        AlarmManager manager = (AlarmManager) service;
782        // TODO Move this into Provider
783        rescheduleMissedAlarms(cr, this, manager);
784        updateAlertNotification(this);
785    }
786
787    private static final String SORT_ORDER_ALARMTIME_ASC =
788            CalendarContract.CalendarAlerts.ALARM_TIME + " ASC";
789
790    private static final String WHERE_RESCHEDULE_MISSED_ALARMS =
791            CalendarContract.CalendarAlerts.STATE
792            + "="
793            + CalendarContract.CalendarAlerts.STATE_SCHEDULED
794            + " AND "
795            + CalendarContract.CalendarAlerts.ALARM_TIME
796            + "<?"
797            + " AND "
798            + CalendarContract.CalendarAlerts.ALARM_TIME
799            + ">?"
800            + " AND "
801            + CalendarContract.CalendarAlerts.END + ">=?";
802
803    /**
804     * Searches the CalendarAlerts table for alarms that should have fired but
805     * have not and then reschedules them. This method can be called at boot
806     * time to restore alarms that may have been lost due to a phone reboot.
807     *
808     * @param cr the ContentResolver
809     * @param context the Context
810     * @param manager the AlarmManager
811     */
812    public static final void rescheduleMissedAlarms(ContentResolver cr, Context context,
813            AlarmManager manager) {
814        // Get all the alerts that have been scheduled but have not fired
815        // and should have fired by now and are not too old.
816        long now = System.currentTimeMillis();
817        long ancient = now - DateUtils.DAY_IN_MILLIS;
818        String[] projection = new String[] {
819            CalendarContract.CalendarAlerts.ALARM_TIME,
820        };
821
822        // TODO: construct an explicit SQL query so that we can add
823        // "GROUPBY" instead of doing a sort and de-dup
824        Cursor cursor = cr.query(CalendarAlerts.CONTENT_URI, projection,
825                WHERE_RESCHEDULE_MISSED_ALARMS, (new String[] {
826                        Long.toString(now), Long.toString(ancient), Long.toString(now)
827                }), SORT_ORDER_ALARMTIME_ASC);
828        if (cursor == null) {
829            return;
830        }
831
832        if (DEBUG) {
833            Log.d(TAG, "missed alarms found: " + cursor.getCount());
834        }
835
836        try {
837            long alarmTime = -1;
838
839            while (cursor.moveToNext()) {
840                long newAlarmTime = cursor.getLong(0);
841                if (alarmTime != newAlarmTime) {
842                    if (DEBUG) {
843                        Log.w(TAG, "rescheduling missed alarm. alarmTime: " + newAlarmTime);
844                    }
845                    AlertUtils.scheduleAlarm(context, manager, newAlarmTime);
846                    alarmTime = newAlarmTime;
847                }
848            }
849        } finally {
850            cursor.close();
851        }
852    }
853
854    private final class ServiceHandler extends Handler {
855        public ServiceHandler(Looper looper) {
856            super(looper);
857        }
858
859        @Override
860        public void handleMessage(Message msg) {
861            processMessage(msg);
862            // NOTE: We MUST not call stopSelf() directly, since we need to
863            // make sure the wake lock acquired by AlertReceiver is released.
864            AlertReceiver.finishStartingService(AlertService.this, msg.arg1);
865        }
866    }
867
868    @Override
869    public void onCreate() {
870        HandlerThread thread = new HandlerThread("AlertService",
871                Process.THREAD_PRIORITY_BACKGROUND);
872        thread.start();
873
874        mServiceLooper = thread.getLooper();
875        mServiceHandler = new ServiceHandler(mServiceLooper);
876    }
877
878    @Override
879    public int onStartCommand(Intent intent, int flags, int startId) {
880        if (intent != null) {
881            Message msg = mServiceHandler.obtainMessage();
882            msg.arg1 = startId;
883            msg.obj = intent.getExtras();
884            mServiceHandler.sendMessage(msg);
885        }
886        return START_REDELIVER_INTENT;
887    }
888
889    @Override
890    public void onDestroy() {
891        mServiceLooper.quit();
892    }
893
894    @Override
895    public IBinder onBind(Intent intent) {
896        return null;
897    }
898}
899