AlertService.java revision a27a886892fe3ec5edbc63c0b58e0a988623011a
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.Attendees;
43import android.provider.CalendarContract.CalendarAlerts;
44import android.text.TextUtils;
45import android.util.Log;
46
47import java.util.HashMap;
48
49/**
50 * This service is used to handle calendar event reminders.
51 */
52public class AlertService extends Service {
53    static final boolean DEBUG = true;
54    private static final String TAG = "AlertService";
55
56    private volatile Looper mServiceLooper;
57    private volatile ServiceHandler mServiceHandler;
58
59    private static final String[] ALERT_PROJECTION = new String[] {
60        CalendarAlerts._ID,                     // 0
61        CalendarAlerts.EVENT_ID,                // 1
62        CalendarAlerts.STATE,                   // 2
63        CalendarAlerts.TITLE,                   // 3
64        CalendarAlerts.EVENT_LOCATION,          // 4
65        CalendarAlerts.SELF_ATTENDEE_STATUS,    // 5
66        CalendarAlerts.ALL_DAY,                 // 6
67        CalendarAlerts.ALARM_TIME,              // 7
68        CalendarAlerts.MINUTES,                 // 8
69        CalendarAlerts.BEGIN,                   // 9
70        CalendarAlerts.END,                     // 10
71    };
72
73    private static final int ALERT_INDEX_ID = 0;
74    private static final int ALERT_INDEX_EVENT_ID = 1;
75    private static final int ALERT_INDEX_STATE = 2;
76    private static final int ALERT_INDEX_TITLE = 3;
77    private static final int ALERT_INDEX_EVENT_LOCATION = 4;
78    private static final int ALERT_INDEX_SELF_ATTENDEE_STATUS = 5;
79    private static final int ALERT_INDEX_ALL_DAY = 6;
80    private static final int ALERT_INDEX_ALARM_TIME = 7;
81    private static final int ALERT_INDEX_MINUTES = 8;
82    private static final int ALERT_INDEX_BEGIN = 9;
83    private static final int ALERT_INDEX_END = 10;
84
85    private static final String ACTIVE_ALERTS_SELECTION = "(" + CalendarAlerts.STATE + "=? OR "
86            + CalendarAlerts.STATE + "=?) AND " + CalendarAlerts.ALARM_TIME + "<=";
87
88    private static final String[] ACTIVE_ALERTS_SELECTION_ARGS = new String[] {
89            Integer.toString(CalendarAlerts.FIRED), Integer.toString(CalendarAlerts.SCHEDULED)
90    };
91
92    private static final String ACTIVE_ALERTS_SORT = "begin DESC, end DESC";
93
94    void processMessage(Message msg) {
95        Bundle bundle = (Bundle) msg.obj;
96
97        // On reboot, update the notification bar with the contents of the
98        // CalendarAlerts table.
99        String action = bundle.getString("action");
100        if (DEBUG) {
101            Log.d(TAG, "" + bundle.getLong(android.provider.CalendarContract.CalendarAlerts.ALARM_TIME)
102                    + " Action = " + action);
103        }
104
105        if (action.equals(Intent.ACTION_BOOT_COMPLETED)
106                || action.equals(Intent.ACTION_TIME_CHANGED)) {
107            doTimeChanged();
108            return;
109        }
110
111        if (!action.equals(android.provider.CalendarContract.ACTION_EVENT_REMINDER)
112                && !action.equals(Intent.ACTION_LOCALE_CHANGED)) {
113            Log.w(TAG, "Invalid action: " + action);
114            return;
115        }
116
117        updateAlertNotification(this);
118    }
119
120    static boolean updateAlertNotification(Context context) {
121        ContentResolver cr = context.getContentResolver();
122        final long currentTime = System.currentTimeMillis();
123
124        Cursor alertCursor = CalendarAlerts.query(cr, ALERT_PROJECTION, ACTIVE_ALERTS_SELECTION
125                + currentTime, ACTIVE_ALERTS_SELECTION_ARGS, ACTIVE_ALERTS_SORT);
126
127        if (alertCursor == null || alertCursor.getCount() == 0) {
128            if (alertCursor != null) {
129                alertCursor.close();
130            }
131
132            if (DEBUG) Log.d(TAG, "No fired or scheduled alerts");
133            NotificationManager nm =
134                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
135            nm.cancel(0);
136            return false;
137        }
138
139        if (DEBUG) {
140            Log.d(TAG, "alert count:" + alertCursor.getCount());
141        }
142
143        String notificationEventName = null;
144        String notificationEventLocation = null;
145        long notificationEventBegin = 0;
146        int notificationEventStatus = 0;
147        boolean notificationEventAllDay = true;
148        HashMap<Long, Long> eventIds = new HashMap<Long, Long>();
149        int numReminders = 0;
150        int numFired = 0;
151        try {
152            while (alertCursor.moveToNext()) {
153                final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
154                final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
155                final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
156                final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
157                final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
158                final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS);
159                final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED;
160                final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
161                final long endTime = alertCursor.getLong(ALERT_INDEX_END);
162                final Uri alertUri = ContentUris
163                        .withAppendedId(CalendarAlerts.CONTENT_URI, alertId);
164                final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
165                int state = alertCursor.getInt(ALERT_INDEX_STATE);
166                final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;
167
168                if (DEBUG) {
169                    Log.d(TAG, "alarmTime:" + alarmTime + " alertId:" + alertId
170                            + " eventId:" + eventId + " state: " + state + " minutes:" + minutes
171                            + " declined:" + declined + " beginTime:" + beginTime
172                            + " endTime:" + endTime);
173                }
174
175                ContentValues values = new ContentValues();
176                int newState = -1;
177
178                // Uncomment for the behavior of clearing out alerts after the
179                // events ended. b/1880369
180                //
181                // if (endTime < currentTime) {
182                //     newState = CalendarAlerts.DISMISSED;
183                // } else
184
185                // Remove declined events
186                if (!declined) {
187                    // Don't count duplicate alerts for the same event
188                    if (eventIds.put(eventId, beginTime) == null) {
189                        numReminders++;
190                    }
191
192                    if (state == CalendarAlerts.SCHEDULED) {
193                        newState = CalendarAlerts.FIRED;
194                        numFired++;
195
196                        // Record the received time in the CalendarAlerts table.
197                        // This is useful for finding bugs that cause alarms to be
198                        // missed or delayed.
199                        values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
200                    }
201                } else {
202                    newState = CalendarAlerts.DISMISSED;
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