AlertService.java revision 43ffa461b738692925a94c005c90ff60757455a7
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.calendar.alerts;
18
19import com.android.calendar.GeneralPreferences;
20import com.android.calendar.R;
21
22import android.app.AlarmManager;
23import android.app.Notification;
24import android.app.NotificationManager;
25import android.app.Service;
26import android.content.ContentResolver;
27import android.content.ContentUris;
28import android.content.ContentValues;
29import android.content.Context;
30import android.content.Intent;
31import android.content.SharedPreferences;
32import android.database.Cursor;
33import android.media.AudioManager;
34import android.net.Uri;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.HandlerThread;
38import android.os.IBinder;
39import android.os.Looper;
40import android.os.Message;
41import android.os.Process;
42import android.provider.CalendarContract;
43import android.provider.CalendarContract.Attendees;
44import android.provider.CalendarContract.CalendarAlerts;
45import android.text.TextUtils;
46import android.text.format.DateUtils;
47import android.util.Log;
48
49import java.util.HashMap;
50
51/**
52 * This service is used to handle calendar event reminders.
53 */
54public class AlertService extends Service {
55    static final boolean DEBUG = false;
56    private static final String TAG = "AlertService";
57
58    private volatile Looper mServiceLooper;
59    private volatile ServiceHandler mServiceHandler;
60
61    private static final String[] ALERT_PROJECTION = new String[] {
62        CalendarAlerts._ID,                     // 0
63        CalendarAlerts.EVENT_ID,                // 1
64        CalendarAlerts.STATE,                   // 2
65        CalendarAlerts.TITLE,                   // 3
66        CalendarAlerts.EVENT_LOCATION,          // 4
67        CalendarAlerts.SELF_ATTENDEE_STATUS,    // 5
68        CalendarAlerts.ALL_DAY,                 // 6
69        CalendarAlerts.ALARM_TIME,              // 7
70        CalendarAlerts.MINUTES,                 // 8
71        CalendarAlerts.BEGIN,                   // 9
72        CalendarAlerts.END,                     // 10
73    };
74
75    private static final int ALERT_INDEX_ID = 0;
76    private static final int ALERT_INDEX_EVENT_ID = 1;
77    private static final int ALERT_INDEX_STATE = 2;
78    private static final int ALERT_INDEX_TITLE = 3;
79    private static final int ALERT_INDEX_EVENT_LOCATION = 4;
80    private static final int ALERT_INDEX_SELF_ATTENDEE_STATUS = 5;
81    private static final int ALERT_INDEX_ALL_DAY = 6;
82    private static final int ALERT_INDEX_ALARM_TIME = 7;
83    private static final int ALERT_INDEX_MINUTES = 8;
84    private static final int ALERT_INDEX_BEGIN = 9;
85    private static final int ALERT_INDEX_END = 10;
86
87    private static final String ACTIVE_ALERTS_SELECTION = "(" + CalendarAlerts.STATE + "=? OR "
88            + CalendarAlerts.STATE + "=?) AND " + CalendarAlerts.ALARM_TIME + "<=";
89
90    private static final String[] ACTIVE_ALERTS_SELECTION_ARGS = new String[] {
91            Integer.toString(CalendarAlerts.STATE_FIRED),
92            Integer.toString(CalendarAlerts.STATE_SCHEDULED)
93    };
94
95    private static final String ACTIVE_ALERTS_SORT = "begin DESC, end DESC";
96
97    private static final String DISMISS_OLD_SELECTION = CalendarAlerts.END + "<? AND "
98            + CalendarAlerts.STATE + "=?";
99
100    void processMessage(Message msg) {
101        Bundle bundle = (Bundle) msg.obj;
102
103        // On reboot, update the notification bar with the contents of the
104        // CalendarAlerts table.
105        String action = bundle.getString("action");
106        if (DEBUG) {
107            Log.d(TAG, bundle.getLong(android.provider.CalendarContract.CalendarAlerts.ALARM_TIME)
108                    + " Action = " + action);
109        }
110
111        if (action.equals(Intent.ACTION_BOOT_COMPLETED)
112                || action.equals(Intent.ACTION_TIME_CHANGED)) {
113            doTimeChanged();
114            return;
115        }
116
117        if (!action.equals(android.provider.CalendarContract.ACTION_EVENT_REMINDER)
118                && !action.equals(Intent.ACTION_LOCALE_CHANGED)
119                && !action.equals(AlertReceiver.ACTION_DISMISS_OLD_REMINDERS)) {
120            Log.w(TAG, "Invalid action: " + action);
121            return;
122        }
123        if (action.equals(AlertReceiver.ACTION_DISMISS_OLD_REMINDERS)) {
124            dismissOldAlerts(this);
125        }
126        updateAlertNotification(this);
127    }
128
129    static void dismissOldAlerts(Context context) {
130        ContentResolver cr = context.getContentResolver();
131        final long currentTime = System.currentTimeMillis();
132        ContentValues vals = new ContentValues();
133        vals.put(CalendarAlerts.STATE, CalendarAlerts.STATE_DISMISSED);
134        cr.update(CalendarAlerts.CONTENT_URI, vals, DISMISS_OLD_SELECTION, new String[] {
135                Long.toString(currentTime), Integer.toString(CalendarAlerts.STATE_SCHEDULED)
136        });
137    }
138
139    static boolean updateAlertNotification(Context context) {
140        ContentResolver cr = context.getContentResolver();
141        final long currentTime = System.currentTimeMillis();
142
143        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
144
145        boolean doAlert = prefs.getBoolean(GeneralPreferences.KEY_ALERTS, true);
146        boolean doPopup = prefs.getBoolean(GeneralPreferences.KEY_ALERTS_POPUP, false);
147
148        if (!doAlert) {
149            if (DEBUG) {
150                Log.d(TAG, "alert preference is OFF");
151            }
152
153            // If we shouldn't be showing notifications cancel any existing ones
154            // and return.
155            NotificationManager nm = (NotificationManager) context
156                    .getSystemService(Context.NOTIFICATION_SERVICE);
157            nm.cancelAll();
158            return true;
159        }
160
161        Cursor alertCursor = cr.query(CalendarAlerts.CONTENT_URI, ALERT_PROJECTION,
162                (ACTIVE_ALERTS_SELECTION + currentTime), ACTIVE_ALERTS_SELECTION_ARGS,
163                ACTIVE_ALERTS_SORT);
164
165        if (alertCursor == null || alertCursor.getCount() == 0) {
166            if (alertCursor != null) {
167                alertCursor.close();
168            }
169
170            if (DEBUG) Log.d(TAG, "No fired or scheduled alerts");
171            NotificationManager nm =
172                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
173            nm.cancel(0);
174            return false;
175        }
176
177        if (DEBUG) {
178            Log.d(TAG, "alert count:" + alertCursor.getCount());
179        }
180
181        String notificationEventName = null;
182        String notificationEventLocation = null;
183        long notificationEventBegin = 0;
184        int notificationEventStatus = 0;
185        boolean notificationEventAllDay = true;
186        HashMap<Long, Long> eventIds = new HashMap<Long, Long>();
187        int numReminders = 0;
188        int numFired = 0;
189        try {
190            while (alertCursor.moveToNext()) {
191                final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
192                final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
193                final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
194                final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
195                final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
196                final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS);
197                final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED;
198                final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
199                final long endTime = alertCursor.getLong(ALERT_INDEX_END);
200                final Uri alertUri = ContentUris
201                        .withAppendedId(CalendarAlerts.CONTENT_URI, alertId);
202                final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
203                int state = alertCursor.getInt(ALERT_INDEX_STATE);
204                final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
205
206                if (DEBUG) {
207                    Log.d(TAG, "alarmTime:" + alarmTime + " alertId:" + alertId
208                            + " eventId:" + eventId + " state: " + state + " minutes:" + minutes
209                            + " declined:" + declined + " beginTime:" + beginTime
210                            + " endTime:" + endTime);
211                }
212
213                ContentValues values = new ContentValues();
214                int newState = -1;
215
216                // Uncomment for the behavior of clearing out alerts after the
217                // events ended. b/1880369
218                //
219                // if (endTime < currentTime) {
220                //     newState = CalendarAlerts.DISMISSED;
221                // } else
222
223                // Remove declined events
224                if (!declined) {
225                    // Don't count duplicate alerts for the same event
226                    if (eventIds.put(eventId, beginTime) == null) {
227                        numReminders++;
228                    }
229
230                    if (state == CalendarAlerts.STATE_SCHEDULED) {
231                        newState = CalendarAlerts.STATE_FIRED;
232                        numFired++;
233
234                        // Record the received time in the CalendarAlerts table.
235                        // This is useful for finding bugs that cause alarms to be
236                        // missed or delayed.
237                        values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
238                    }
239                } else {
240                    newState = CalendarAlerts.STATE_DISMISSED;
241                }
242
243                // Update row if state changed
244                if (newState != -1) {
245                    values.put(CalendarAlerts.STATE, newState);
246                    state = newState;
247                }
248
249                if (state == CalendarAlerts.STATE_FIRED) {
250                    // Record the time posting to notification manager.
251                    // This is used for debugging missed alarms.
252                    values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
253                }
254
255                // Write row to if anything changed
256                if (values.size() > 0) cr.update(alertUri, values, null, null);
257
258                if (state != CalendarAlerts.STATE_FIRED) {
259                    continue;
260                }
261
262                // Pick an Event title for the notification panel by the latest
263                // alertTime and give prefer accepted events in case of ties.
264                int newStatus;
265                switch (status) {
266                    case Attendees.ATTENDEE_STATUS_ACCEPTED:
267                        newStatus = 2;
268                        break;
269                    case Attendees.ATTENDEE_STATUS_TENTATIVE:
270                        newStatus = 1;
271                        break;
272                    default:
273                        newStatus = 0;
274                }
275
276                // TODO Prioritize by "primary" calendar
277                // Assumes alerts are sorted by begin time in reverse
278                if (notificationEventName == null
279                        || (notificationEventBegin <= beginTime &&
280                                notificationEventStatus < newStatus)) {
281                    notificationEventName = eventName;
282                    notificationEventLocation = location;
283                    notificationEventBegin = beginTime;
284                    notificationEventStatus = newStatus;
285                    notificationEventAllDay = allDay;
286                }
287            }
288        } finally {
289            if (alertCursor != null) {
290                alertCursor.close();
291            }
292        }
293
294        boolean quietUpdate = numFired == 0;
295        boolean highPriority = numFired > 0 && doPopup;
296        postNotification(context, prefs, notificationEventName, notificationEventLocation,
297                numReminders, quietUpdate, highPriority, notificationEventBegin,
298                notificationEventAllDay);
299
300        return true;
301    }
302
303    private static void postNotification(Context context, SharedPreferences prefs,
304            String eventName, String location, int numReminders,
305            boolean quietUpdate, boolean highPriority, long startMillis, boolean allDay) {
306        if (DEBUG) {
307            Log.d(TAG, "###### creating new alarm notification, numReminders: " + numReminders
308                    + (quietUpdate ? " QUIET" : " loud")
309                    + (highPriority ? " high-priority" : ""));
310        }
311
312        NotificationManager nm =
313                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
314
315        if (numReminders == 0) {
316            nm.cancel(0);
317            return;
318        }
319
320        Notification notification = AlertReceiver.makeNewAlertNotification(context, eventName,
321                location, numReminders, highPriority, startMillis, allDay);
322        notification.defaults |= Notification.DEFAULT_LIGHTS;
323
324        // Quietly update notification bar. Nothing new. Maybe something just got deleted.
325        if (!quietUpdate) {
326            // Flash ticker in status bar
327            notification.tickerText = eventName;
328            if (!TextUtils.isEmpty(location)) {
329                notification.tickerText = eventName + " - " + location;
330            }
331
332            // Generate either a pop-up dialog, status bar notification, or
333            // neither. Pop-up dialog and status bar notification may include a
334            // sound, an alert, or both. A status bar notification also includes
335            // a toast.
336
337            // Find out the circumstances under which to vibrate.
338            // Migrate from pre-Froyo boolean setting if necessary.
339            String vibrateWhen; // "always" or "silent" or "never"
340            if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN))
341            {
342                // Look up Froyo setting
343                vibrateWhen =
344                    prefs.getString(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN, null);
345            } else if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE)) {
346                // No Froyo setting. Migrate pre-Froyo setting to new Froyo-defined value.
347                boolean vibrate =
348                    prefs.getBoolean(GeneralPreferences.KEY_ALERTS_VIBRATE, false);
349                vibrateWhen = vibrate ?
350                    context.getString(R.string.prefDefault_alerts_vibrate_true) :
351                    context.getString(R.string.prefDefault_alerts_vibrate_false);
352            } else {
353                // No setting. Use Froyo-defined default.
354                vibrateWhen = context.getString(R.string.prefDefault_alerts_vibrateWhen);
355            }
356            boolean vibrateAlways = vibrateWhen.equals("always");
357            boolean vibrateSilent = vibrateWhen.equals("silent");
358            AudioManager audioManager =
359                (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
360            boolean nowSilent =
361                audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
362
363            // Possibly generate a vibration
364            if (vibrateAlways || (vibrateSilent && nowSilent)) {
365                notification.defaults |= Notification.DEFAULT_VIBRATE;
366            }
367
368            // Possibly generate a sound. If 'Silent' is chosen, the ringtone
369            // string will be empty.
370            String reminderRingtone = prefs.getString(
371                    GeneralPreferences.KEY_ALERTS_RINGTONE, null);
372            notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
373                    .parse(reminderRingtone);
374        }
375
376        nm.notify(0, notification);
377    }
378
379    private void doTimeChanged() {
380        ContentResolver cr = getContentResolver();
381        Object service = getSystemService(Context.ALARM_SERVICE);
382        AlarmManager manager = (AlarmManager) service;
383        // TODO Move this into Provider
384        rescheduleMissedAlarms(cr, this, manager);
385        updateAlertNotification(this);
386    }
387
388    private static final String SORT_ORDER_ALARMTIME_ASC =
389            CalendarContract.CalendarAlerts.ALARM_TIME + " ASC";
390
391    private static final String WHERE_RESCHEDULE_MISSED_ALARMS =
392            CalendarContract.CalendarAlerts.STATE
393            + "="
394            + CalendarContract.CalendarAlerts.STATE_SCHEDULED
395            + " AND "
396            + CalendarContract.CalendarAlerts.ALARM_TIME
397            + "<?"
398            + " AND "
399            + CalendarContract.CalendarAlerts.ALARM_TIME
400            + ">?"
401            + " AND "
402            + CalendarContract.CalendarAlerts.END + ">=?";
403
404    /**
405     * Searches the CalendarAlerts table for alarms that should have fired but
406     * have not and then reschedules them. This method can be called at boot
407     * time to restore alarms that may have been lost due to a phone reboot.
408     *
409     * @param cr the ContentResolver
410     * @param context the Context
411     * @param manager the AlarmManager
412     */
413    public static final void rescheduleMissedAlarms(ContentResolver cr, Context context,
414            AlarmManager manager) {
415        // Get all the alerts that have been scheduled but have not fired
416        // and should have fired by now and are not too old.
417        long now = System.currentTimeMillis();
418        long ancient = now - DateUtils.DAY_IN_MILLIS;
419        String[] projection = new String[] {
420            CalendarContract.CalendarAlerts.ALARM_TIME,
421        };
422
423        // TODO: construct an explicit SQL query so that we can add
424        // "GROUPBY" instead of doing a sort and de-dup
425        Cursor cursor = cr.query(CalendarAlerts.CONTENT_URI, projection,
426                WHERE_RESCHEDULE_MISSED_ALARMS, (new String[] {
427                        Long.toString(now), Long.toString(ancient), Long.toString(now)
428                }), SORT_ORDER_ALARMTIME_ASC);
429        if (cursor == null) {
430            return;
431        }
432
433        if (DEBUG) {
434            Log.d(TAG, "missed alarms found: " + cursor.getCount());
435        }
436
437        try {
438            long alarmTime = -1;
439
440            while (cursor.moveToNext()) {
441                long newAlarmTime = cursor.getLong(0);
442                if (alarmTime != newAlarmTime) {
443                    if (DEBUG) {
444                        Log.w(TAG, "rescheduling missed alarm. alarmTime: " + newAlarmTime);
445                    }
446                    AlertActivity.scheduleAlarm(context, manager, newAlarmTime);
447                    alarmTime = newAlarmTime;
448                }
449            }
450        } finally {
451            cursor.close();
452        }
453    }
454
455    private final class ServiceHandler extends Handler {
456        public ServiceHandler(Looper looper) {
457            super(looper);
458        }
459
460        @Override
461        public void handleMessage(Message msg) {
462            processMessage(msg);
463            // NOTE: We MUST not call stopSelf() directly, since we need to
464            // make sure the wake lock acquired by AlertReceiver is released.
465            AlertReceiver.finishStartingService(AlertService.this, msg.arg1);
466        }
467    }
468
469    @Override
470    public void onCreate() {
471        HandlerThread thread = new HandlerThread("AlertService",
472                Process.THREAD_PRIORITY_BACKGROUND);
473        thread.start();
474
475        mServiceLooper = thread.getLooper();
476        mServiceHandler = new ServiceHandler(mServiceLooper);
477    }
478
479    @Override
480    public int onStartCommand(Intent intent, int flags, int startId) {
481        if (intent != null) {
482            Message msg = mServiceHandler.obtainMessage();
483            msg.arg1 = startId;
484            msg.obj = intent.getExtras();
485            mServiceHandler.sendMessage(msg);
486        }
487        return START_REDELIVER_INTENT;
488    }
489
490    @Override
491    public void onDestroy() {
492        mServiceLooper.quit();
493    }
494
495    @Override
496    public IBinder onBind(Intent intent) {
497        return null;
498    }
499}
500