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