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