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