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