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