AlertService.java revision 23e7da3eacee7bceb105cdfc7b5329c7a43846d5
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.CalendarPreferenceActivity;
20import com.android.calendar.R;
21import com.android.calendar.R.string;
22
23import android.app.AlarmManager;
24import android.app.Notification;
25import android.app.NotificationManager;
26import android.app.Service;
27import android.content.ContentResolver;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
32import android.content.SharedPreferences;
33import android.database.Cursor;
34import android.media.AudioManager;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.HandlerThread;
39import android.os.IBinder;
40import android.os.Looper;
41import android.os.Message;
42import android.os.Process;
43import android.preference.PreferenceManager;
44import android.provider.Calendar.Attendees;
45import android.provider.Calendar.CalendarAlerts;
46import android.text.TextUtils;
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 = true;
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.FIRED), Integer.toString(CalendarAlerts.SCHEDULED)
92    };
93
94    private static final String ACTIVE_ALERTS_SORT = "begin DESC, end DESC";
95
96    @SuppressWarnings("deprecation")
97    void processMessage(Message msg) {
98        Bundle bundle = (Bundle) msg.obj;
99
100        // On reboot, update the notification bar with the contents of the
101        // CalendarAlerts table.
102        String action = bundle.getString("action");
103        if (DEBUG) {
104            Log.d(TAG, "" + bundle.getLong(android.provider.Calendar.CalendarAlerts.ALARM_TIME)
105                    + " Action = " + action);
106        }
107
108        if (action.equals(Intent.ACTION_BOOT_COMPLETED)
109                || action.equals(Intent.ACTION_TIME_CHANGED)) {
110            doTimeChanged();
111            return;
112        }
113
114        if (!action.equals(android.provider.Calendar.EVENT_REMINDER_ACTION)
115                && !action.equals(Intent.ACTION_LOCALE_CHANGED)) {
116            Log.w(TAG, "Invalid action: " + action);
117            return;
118        }
119
120        updateAlertNotification(this);
121    }
122
123    static boolean updateAlertNotification(Context context) {
124        ContentResolver cr = context.getContentResolver();
125        final long currentTime = System.currentTimeMillis();
126
127        Cursor alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, ACTIVE_ALERTS_SELECTION
128                + currentTime, ACTIVE_ALERTS_SELECTION_ARGS, 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        HashMap<Long, Long> eventIds = new HashMap<Long, Long>();
151        int numReminders = 0;
152        int numFired = 0;
153        try {
154            while (alertCursor.moveToNext()) {
155                final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
156                final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
157                final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
158                final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
159                final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
160                final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
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
170                if (DEBUG) {
171                    Log.d(TAG, "alarmTime:" + alarmTime + " alertId:" + alertId
172                            + " eventId:" + eventId + " state: " + state + " minutes:" + minutes
173                            + " declined:" + declined + " beginTime:" + beginTime
174                            + " endTime:" + endTime);
175                }
176
177                ContentValues values = new ContentValues();
178                int newState = -1;
179
180                // Uncomment for the behavior of clearing out alerts after the
181                // events ended. b/1880369
182                //
183                // if (endTime < currentTime) {
184                //     newState = CalendarAlerts.DISMISSED;
185                // } else
186
187                // Remove declined events and duplicate alerts for the same event
188                if (!declined && eventIds.put(eventId, beginTime) == null) {
189                    numReminders++;
190                    if (state == CalendarAlerts.SCHEDULED) {
191                        newState = CalendarAlerts.FIRED;
192                        numFired++;
193
194                        // Record the received time in the CalendarAlerts table.
195                        // This is useful for finding bugs that cause alarms to be
196                        // missed or delayed.
197                        values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
198                    }
199                } else {
200                    newState = CalendarAlerts.DISMISSED;
201                    if (DEBUG) {
202                        if (!declined) Log.d(TAG, "dropping dup alert for event " + eventId);
203                    }
204                }
205
206                // Update row if state changed
207                if (newState != -1) {
208                    values.put(CalendarAlerts.STATE, newState);
209                    state = newState;
210                }
211
212                if (state == CalendarAlerts.FIRED) {
213                    // Record the time posting to notification manager.
214                    // This is used for debugging missed alarms.
215                    values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
216                }
217
218                // Write row to if anything changed
219                if (values.size() > 0) cr.update(alertUri, values, null, null);
220
221                if (state != CalendarAlerts.FIRED) {
222                    continue;
223                }
224
225                // Pick an Event title for the notification panel by the latest
226                // alertTime and give prefer accepted events in case of ties.
227                int newStatus;
228                switch (status) {
229                    case Attendees.ATTENDEE_STATUS_ACCEPTED:
230                        newStatus = 2;
231                        break;
232                    case Attendees.ATTENDEE_STATUS_TENTATIVE:
233                        newStatus = 1;
234                        break;
235                    default:
236                        newStatus = 0;
237                }
238
239                // TODO Prioritize by "primary" calendar
240                // Assumes alerts are sorted by begin time in reverse
241                if (notificationEventName == null
242                        || (notificationEventBegin <= beginTime &&
243                                notificationEventStatus < newStatus)) {
244                    notificationEventName = eventName;
245                    notificationEventLocation = location;
246                    notificationEventBegin = beginTime;
247                    notificationEventStatus = newStatus;
248                }
249            }
250        } finally {
251            if (alertCursor != null) {
252                alertCursor.close();
253            }
254        }
255
256        SharedPreferences prefs = CalendarPreferenceActivity.getSharedPreferences(context);
257
258        boolean doAlert = prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS, true);
259        boolean doPopup = prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS_POPUP, false);
260
261        // TODO check for this before adding stuff to the alerts table.
262        if (!doAlert) {
263            if (DEBUG) {
264                Log.d(TAG, "alert preference is OFF");
265            }
266            return true;
267        }
268
269        boolean quietUpdate = numFired == 0;
270        boolean highPriority = numFired > 0 && doPopup;
271        postNotification(context, prefs, notificationEventName, notificationEventLocation,
272                numReminders, quietUpdate, highPriority);
273
274        return true;
275    }
276
277    private static void postNotification(Context context, SharedPreferences prefs,
278            String eventName, String location, int numReminders,
279            boolean quietUpdate, boolean highPriority) {
280        if (DEBUG) {
281            Log.d(TAG, "###### creating new alarm notification, numReminders: " + numReminders
282                    + (quietUpdate ? " QUIET" : " loud")
283                    + (highPriority ? " high-priority" : ""));
284        }
285
286        NotificationManager nm =
287                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
288
289        if (numReminders == 0) {
290            nm.cancel(0);
291            return;
292        }
293
294        Notification notification = AlertReceiver.makeNewAlertNotification(context, eventName,
295                location, numReminders, highPriority);
296        notification.defaults |= Notification.DEFAULT_LIGHTS;
297
298        // Quietly update notification bar. Nothing new. Maybe something just got deleted.
299        if (!quietUpdate) {
300            // Flash ticker in status bar
301            notification.tickerText = eventName;
302            if (!TextUtils.isEmpty(location)) {
303                notification.tickerText = eventName + " - " + location;
304            }
305
306            // Generate either a pop-up dialog, status bar notification, or
307            // neither. Pop-up dialog and status bar notification may include a
308            // sound, an alert, or both. A status bar notification also includes
309            // a toast.
310
311            // Find out the circumstances under which to vibrate.
312            // Migrate from pre-Froyo boolean setting if necessary.
313            String vibrateWhen; // "always" or "silent" or "never"
314            if(prefs.contains(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE_WHEN))
315            {
316                // Look up Froyo setting
317                vibrateWhen =
318                    prefs.getString(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE_WHEN, null);
319            } else if(prefs.contains(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE)) {
320                // No Froyo setting. Migrate pre-Froyo setting to new Froyo-defined value.
321                boolean vibrate =
322                    prefs.getBoolean(CalendarPreferenceActivity.KEY_ALERTS_VIBRATE, false);
323                vibrateWhen = vibrate ?
324                    context.getString(R.string.prefDefault_alerts_vibrate_true) :
325                    context.getString(R.string.prefDefault_alerts_vibrate_false);
326            } else {
327                // No setting. Use Froyo-defined default.
328                vibrateWhen = context.getString(R.string.prefDefault_alerts_vibrateWhen);
329            }
330            boolean vibrateAlways = vibrateWhen.equals("always");
331            boolean vibrateSilent = vibrateWhen.equals("silent");
332            AudioManager audioManager =
333                (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
334            boolean nowSilent =
335                audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
336
337            // Possibly generate a vibration
338            if (vibrateAlways || (vibrateSilent && nowSilent)) {
339                notification.defaults |= Notification.DEFAULT_VIBRATE;
340            }
341
342            // Possibly generate a sound. If 'Silent' is chosen, the ringtone
343            // string will be empty.
344            String reminderRingtone = prefs.getString(
345                    CalendarPreferenceActivity.KEY_ALERTS_RINGTONE, null);
346            notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
347                    .parse(reminderRingtone);
348        }
349
350        nm.notify(0, notification);
351    }
352
353    private void doTimeChanged() {
354        ContentResolver cr = getContentResolver();
355        Object service = getSystemService(Context.ALARM_SERVICE);
356        AlarmManager manager = (AlarmManager) service;
357        CalendarAlerts.rescheduleMissedAlarms(cr, this, manager);
358        updateAlertNotification(this);
359    }
360
361    private final class ServiceHandler extends Handler {
362        public ServiceHandler(Looper looper) {
363            super(looper);
364        }
365
366        @Override
367        public void handleMessage(Message msg) {
368            processMessage(msg);
369            // NOTE: We MUST not call stopSelf() directly, since we need to
370            // make sure the wake lock acquired by AlertReceiver is released.
371            AlertReceiver.finishStartingService(AlertService.this, msg.arg1);
372        }
373    }
374
375    @Override
376    public void onCreate() {
377        HandlerThread thread = new HandlerThread("AlertService",
378                Process.THREAD_PRIORITY_BACKGROUND);
379        thread.start();
380
381        mServiceLooper = thread.getLooper();
382        mServiceHandler = new ServiceHandler(mServiceLooper);
383    }
384
385    @Override
386    public int onStartCommand(Intent intent, int flags, int startId) {
387        if (intent != null) {
388            Message msg = mServiceHandler.obtainMessage();
389            msg.arg1 = startId;
390            msg.obj = intent.getExtras();
391            mServiceHandler.sendMessage(msg);
392        }
393        return START_REDELIVER_INTENT;
394    }
395
396    @Override
397    public void onDestroy() {
398        mServiceLooper.quit();
399    }
400
401    @Override
402    public IBinder onBind(Intent intent) {
403        return null;
404    }
405}
406