AlertService.java revision 7321a0630aca3e5093d12f0e4f55da77620f53ed
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;
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.provider.Calendar.Attendees;
44import android.provider.Calendar.CalendarAlerts;
45import android.text.TextUtils;
46import android.util.Log;
47
48import java.util.HashMap;
49
50/**
51 * This service is used to handle calendar event reminders.
52 */
53public class AlertService extends Service {
54    static final boolean DEBUG = true;
55    private static final String TAG = "AlertService";
56
57    private volatile Looper mServiceLooper;
58    private volatile ServiceHandler mServiceHandler;
59
60    private static final String[] ALERT_PROJECTION = new String[] {
61        CalendarAlerts._ID,                     // 0
62        CalendarAlerts.EVENT_ID,                // 1
63        CalendarAlerts.STATE,                   // 2
64        CalendarAlerts.TITLE,                   // 3
65        CalendarAlerts.EVENT_LOCATION,          // 4
66        CalendarAlerts.SELF_ATTENDEE_STATUS,    // 5
67        CalendarAlerts.ALL_DAY,                 // 6
68        CalendarAlerts.ALARM_TIME,              // 7
69        CalendarAlerts.MINUTES,                 // 8
70        CalendarAlerts.BEGIN,                   // 9
71        CalendarAlerts.END,                     // 10
72    };
73
74    private static final int ALERT_INDEX_ID = 0;
75    private static final int ALERT_INDEX_EVENT_ID = 1;
76    private static final int ALERT_INDEX_STATE = 2;
77    private static final int ALERT_INDEX_TITLE = 3;
78    private static final int ALERT_INDEX_EVENT_LOCATION = 4;
79    private static final int ALERT_INDEX_SELF_ATTENDEE_STATUS = 5;
80    private static final int ALERT_INDEX_ALL_DAY = 6;
81    private static final int ALERT_INDEX_ALARM_TIME = 7;
82    private static final int ALERT_INDEX_MINUTES = 8;
83    private static final int ALERT_INDEX_BEGIN = 9;
84    private static final int ALERT_INDEX_END = 10;
85
86    private static final String ACTIVE_ALERTS_SELECTION = "(" + CalendarAlerts.STATE + "=? OR "
87            + CalendarAlerts.STATE + "=?) AND " + CalendarAlerts.ALARM_TIME + "<=";
88
89    private static final String[] ACTIVE_ALERTS_SELECTION_ARGS = new String[] {
90            Integer.toString(CalendarAlerts.FIRED), Integer.toString(CalendarAlerts.SCHEDULED)
91    };
92
93    private static final String ACTIVE_ALERTS_SORT = "begin DESC, end DESC";
94
95    void processMessage(Message msg) {
96        Bundle bundle = (Bundle) msg.obj;
97
98        // On reboot, update the notification bar with the contents of the
99        // CalendarAlerts table.
100        String action = bundle.getString("action");
101        if (DEBUG) {
102            Log.d(TAG, "" + bundle.getLong(android.provider.Calendar.CalendarAlerts.ALARM_TIME)
103                    + " Action = " + action);
104        }
105
106        if (action.equals(Intent.ACTION_BOOT_COMPLETED)
107                || action.equals(Intent.ACTION_TIME_CHANGED)) {
108            doTimeChanged();
109            return;
110        }
111
112        if (!action.equals(android.provider.Calendar.EVENT_REMINDER_ACTION)
113                && !action.equals(Intent.ACTION_LOCALE_CHANGED)) {
114            Log.w(TAG, "Invalid action: " + action);
115            return;
116        }
117
118        updateAlertNotification(this);
119    }
120
121    static boolean updateAlertNotification(Context context) {
122        ContentResolver cr = context.getContentResolver();
123        final long currentTime = System.currentTimeMillis();
124
125        Cursor alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, ACTIVE_ALERTS_SELECTION
126                + currentTime, ACTIVE_ALERTS_SELECTION_ARGS, ACTIVE_ALERTS_SORT);
127
128        if (alertCursor == null || alertCursor.getCount() == 0) {
129            if (alertCursor != null) {
130                alertCursor.close();
131            }
132
133            if (DEBUG) Log.d(TAG, "No fired or scheduled alerts");
134            NotificationManager nm =
135                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
136            nm.cancel(0);
137            return false;
138        }
139
140        if (DEBUG) {
141            Log.d(TAG, "alert count:" + alertCursor.getCount());
142        }
143
144        String notificationEventName = null;
145        String notificationEventLocation = null;
146        long notificationEventBegin = 0;
147        int notificationEventStatus = 0;
148        boolean notificationEventAllDay = true;
149        HashMap<Long, Long> eventIds = new HashMap<Long, Long>();
150        int numReminders = 0;
151        int numFired = 0;
152        try {
153            while (alertCursor.moveToNext()) {
154                final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
155                final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
156                final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
157                final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
158                final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
159                final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS);
160                final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED;
161                final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
162                final long endTime = alertCursor.getLong(ALERT_INDEX_END);
163                final Uri alertUri = ContentUris
164                        .withAppendedId(CalendarAlerts.CONTENT_URI, alertId);
165                final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
166                int state = alertCursor.getInt(ALERT_INDEX_STATE);
167                final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
168
169                if (DEBUG) {
170                    Log.d(TAG, "alarmTime:" + alarmTime + " alertId:" + alertId
171                            + " eventId:" + eventId + " state: " + state + " minutes:" + minutes
172                            + " declined:" + declined + " beginTime:" + beginTime
173                            + " endTime:" + endTime);
174                }
175
176                ContentValues values = new ContentValues();
177                int newState = -1;
178
179                // Uncomment for the behavior of clearing out alerts after the
180                // events ended. b/1880369
181                //
182                // if (endTime < currentTime) {
183                //     newState = CalendarAlerts.DISMISSED;
184                // } else
185
186                // Remove declined events and duplicate alerts for the same event
187                if (!declined && eventIds.put(eventId, beginTime) == null) {
188                    numReminders++;
189                    if (state == CalendarAlerts.SCHEDULED) {
190                        newState = CalendarAlerts.FIRED;
191                        numFired++;
192
193                        // Record the received time in the CalendarAlerts table.
194                        // This is useful for finding bugs that cause alarms to be
195                        // missed or delayed.
196                        values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
197                    }
198                } else {
199                    newState = CalendarAlerts.DISMISSED;
200                    if (DEBUG) {
201                        if (!declined) Log.d(TAG, "dropping dup alert for event " + eventId);
202                    }
203                }
204
205                // Update row if state changed
206                if (newState != -1) {
207                    values.put(CalendarAlerts.STATE, newState);
208                    state = newState;
209                }
210
211                if (state == CalendarAlerts.FIRED) {
212                    // Record the time posting to notification manager.
213                    // This is used for debugging missed alarms.
214                    values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
215                }
216
217                // Write row to if anything changed
218                if (values.size() > 0) cr.update(alertUri, values, null, null);
219
220                if (state != CalendarAlerts.FIRED) {
221                    continue;
222                }
223
224                // Pick an Event title for the notification panel by the latest
225                // alertTime and give prefer accepted events in case of ties.
226                int newStatus;
227                switch (status) {
228                    case Attendees.ATTENDEE_STATUS_ACCEPTED:
229                        newStatus = 2;
230                        break;
231                    case Attendees.ATTENDEE_STATUS_TENTATIVE:
232                        newStatus = 1;
233                        break;
234                    default:
235                        newStatus = 0;
236                }
237
238                // TODO Prioritize by "primary" calendar
239                // Assumes alerts are sorted by begin time in reverse
240                if (notificationEventName == null
241                        || (notificationEventBegin <= beginTime &&
242                                notificationEventStatus < newStatus)) {
243                    notificationEventName = eventName;
244                    notificationEventLocation = location;
245                    notificationEventBegin = beginTime;
246                    notificationEventStatus = newStatus;
247                    notificationEventAllDay = allDay;
248                }
249            }
250        } finally {
251            if (alertCursor != null) {
252                alertCursor.close();
253            }
254        }
255
256        SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context);
257
258        boolean doAlert = prefs.getBoolean(GeneralPreferences.KEY_ALERTS, true);
259        boolean doPopup = prefs.getBoolean(GeneralPreferences.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, notificationEventBegin,
273                notificationEventAllDay);
274
275        return true;
276    }
277
278    private static void postNotification(Context context, SharedPreferences prefs,
279            String eventName, String location, int numReminders,
280            boolean quietUpdate, boolean highPriority, long startMillis, boolean allDay) {
281        if (DEBUG) {
282            Log.d(TAG, "###### creating new alarm notification, numReminders: " + numReminders
283                    + (quietUpdate ? " QUIET" : " loud")
284                    + (highPriority ? " high-priority" : ""));
285        }
286
287        NotificationManager nm =
288                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
289
290        if (numReminders == 0) {
291            nm.cancel(0);
292            return;
293        }
294
295        Notification notification = AlertReceiver.makeNewAlertNotification(context, eventName,
296                location, numReminders, highPriority, startMillis, allDay);
297        notification.defaults |= Notification.DEFAULT_LIGHTS;
298
299        // Quietly update notification bar. Nothing new. Maybe something just got deleted.
300        if (!quietUpdate) {
301            // Flash ticker in status bar
302            notification.tickerText = eventName;
303            if (!TextUtils.isEmpty(location)) {
304                notification.tickerText = eventName + " - " + location;
305            }
306
307            // Generate either a pop-up dialog, status bar notification, or
308            // neither. Pop-up dialog and status bar notification may include a
309            // sound, an alert, or both. A status bar notification also includes
310            // a toast.
311
312            // Find out the circumstances under which to vibrate.
313            // Migrate from pre-Froyo boolean setting if necessary.
314            String vibrateWhen; // "always" or "silent" or "never"
315            if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN))
316            {
317                // Look up Froyo setting
318                vibrateWhen =
319                    prefs.getString(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN, null);
320            } else if(prefs.contains(GeneralPreferences.KEY_ALERTS_VIBRATE)) {
321                // No Froyo setting. Migrate pre-Froyo setting to new Froyo-defined value.
322                boolean vibrate =
323                    prefs.getBoolean(GeneralPreferences.KEY_ALERTS_VIBRATE, false);
324                vibrateWhen = vibrate ?
325                    context.getString(R.string.prefDefault_alerts_vibrate_true) :
326                    context.getString(R.string.prefDefault_alerts_vibrate_false);
327            } else {
328                // No setting. Use Froyo-defined default.
329                vibrateWhen = context.getString(R.string.prefDefault_alerts_vibrateWhen);
330            }
331            boolean vibrateAlways = vibrateWhen.equals("always");
332            boolean vibrateSilent = vibrateWhen.equals("silent");
333            AudioManager audioManager =
334                (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
335            boolean nowSilent =
336                audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
337
338            // Possibly generate a vibration
339            if (vibrateAlways || (vibrateSilent && nowSilent)) {
340                notification.defaults |= Notification.DEFAULT_VIBRATE;
341            }
342
343            // Possibly generate a sound. If 'Silent' is chosen, the ringtone
344            // string will be empty.
345            String reminderRingtone = prefs.getString(
346                    GeneralPreferences.KEY_ALERTS_RINGTONE, null);
347            notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri
348                    .parse(reminderRingtone);
349        }
350
351        nm.notify(0, notification);
352    }
353
354    private void doTimeChanged() {
355        ContentResolver cr = getContentResolver();
356        Object service = getSystemService(Context.ALARM_SERVICE);
357        AlarmManager manager = (AlarmManager) service;
358        CalendarAlerts.rescheduleMissedAlarms(cr, this, manager);
359        updateAlertNotification(this);
360    }
361
362    private final class ServiceHandler extends Handler {
363        public ServiceHandler(Looper looper) {
364            super(looper);
365        }
366
367        @Override
368        public void handleMessage(Message msg) {
369            processMessage(msg);
370            // NOTE: We MUST not call stopSelf() directly, since we need to
371            // make sure the wake lock acquired by AlertReceiver is released.
372            AlertReceiver.finishStartingService(AlertService.this, msg.arg1);
373        }
374    }
375
376    @Override
377    public void onCreate() {
378        HandlerThread thread = new HandlerThread("AlertService",
379                Process.THREAD_PRIORITY_BACKGROUND);
380        thread.start();
381
382        mServiceLooper = thread.getLooper();
383        mServiceHandler = new ServiceHandler(mServiceLooper);
384    }
385
386    @Override
387    public int onStartCommand(Intent intent, int flags, int startId) {
388        if (intent != null) {
389            Message msg = mServiceHandler.obtainMessage();
390            msg.arg1 = startId;
391            msg.obj = intent.getExtras();
392            mServiceHandler.sendMessage(msg);
393        }
394        return START_REDELIVER_INTENT;
395    }
396
397    @Override
398    public void onDestroy() {
399        mServiceLooper.quit();
400    }
401
402    @Override
403    public IBinder onBind(Intent intent) {
404        return null;
405    }
406}
407