AlertUtils.java revision 2b66f92853349acac5e75b6ecddf5baecea1505d
1/*
2 * Copyright (C) 2012 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 android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.ContentUris;
22import android.content.ContentValues;
23import android.content.Context;
24import android.content.Intent;
25import android.content.SharedPreferences;
26import android.net.Uri;
27import android.provider.CalendarContract;
28import android.provider.CalendarContract.CalendarAlerts;
29import android.text.TextUtils;
30import android.text.format.DateFormat;
31import android.text.format.DateUtils;
32import android.text.format.Time;
33import android.util.Log;
34
35import com.android.calendar.EventInfoActivity;
36import com.android.calendar.R;
37import com.android.calendar.Utils;
38
39import java.util.Locale;
40import java.util.Map;
41import java.util.TimeZone;
42
43public class AlertUtils {
44    private static final String TAG = "AlertUtils";
45    static final boolean DEBUG = true;
46
47    public static final long SNOOZE_DELAY = 5 * 60 * 1000L;
48
49    // We use one notification id for the expired events notification.  All
50    // other notifications (the 'active' future/concurrent ones) use a unique ID.
51    public static final int EXPIRED_GROUP_NOTIFICATION_ID = 0;
52
53    public static final String EVENT_ID_KEY = "eventid";
54    public static final String EVENT_START_KEY = "eventstart";
55    public static final String EVENT_END_KEY = "eventend";
56    public static final String NOTIFICATION_ID_KEY = "notificationid";
57    public static final String EVENT_IDS_KEY = "eventids";
58    public static final String EVENT_STARTS_KEY = "starts";
59
60    // A flag for using local storage to save alert state instead of the alerts DB table.
61    // This allows the unbundled app to run alongside other calendar apps without eating
62    // alerts from other apps.
63    static boolean BYPASS_DB = true;
64
65    // SharedPrefs table name for storing fired alerts.  This prevents other installed
66    // Calendar apps from eating the alerts.
67    private static final String ALERTS_SHARED_PREFS_NAME = "calendar_alerts";
68
69    // Keyname prefix for the alerts data in SharedPrefs.  The key will contain a combo
70    // of event ID, begin time, and alarm time.  The value will be the fired time.
71    private static final String KEY_FIRED_ALERT_PREFIX = "preference_alert_";
72
73    // The last time the SharedPrefs was scanned and flushed of old alerts data.
74    private static final String KEY_LAST_FLUSH_TIME_MS = "preference_flushTimeMs";
75
76    // The # of days to save alert states in the shared prefs table, before flushing.  This
77    // can be any value, since AlertService will also check for a recent alertTime before
78    // ringing the alert.
79    private static final int FLUSH_INTERVAL_DAYS = 1;
80    private static final int FLUSH_INTERVAL_MS = FLUSH_INTERVAL_DAYS * 24 * 60 * 60 * 1000;
81
82    /**
83     * Creates an AlarmManagerInterface that wraps a real AlarmManager.  The alarm code
84     * was abstracted to an interface to make it testable.
85     */
86    public static AlarmManagerInterface createAlarmManager(Context context) {
87        final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
88        return new AlarmManagerInterface() {
89            @Override
90            public void set(int type, long triggerAtMillis, PendingIntent operation) {
91                mgr.setExact(type, triggerAtMillis, operation);
92            }
93        };
94    }
95
96    /**
97     * Schedules an alarm intent with the system AlarmManager that will notify
98     * listeners when a reminder should be fired. The provider will keep
99     * scheduled reminders up to date but apps may use this to implement snooze
100     * functionality without modifying the reminders table. Scheduled alarms
101     * will generate an intent using AlertReceiver.EVENT_REMINDER_APP_ACTION.
102     *
103     * @param context A context for referencing system resources
104     * @param manager The AlarmManager to use or null
105     * @param alarmTime The time to fire the intent in UTC millis since epoch
106     */
107    public static void scheduleAlarm(Context context, AlarmManagerInterface manager,
108            long alarmTime) {
109        scheduleAlarmHelper(context, manager, alarmTime, false);
110    }
111
112    /**
113     * Schedules the next alarm to silently refresh the notifications.  Note that if there
114     * is a pending silent refresh alarm, it will be replaced with this one.
115     */
116    static void scheduleNextNotificationRefresh(Context context, AlarmManagerInterface manager,
117            long alarmTime) {
118        scheduleAlarmHelper(context, manager, alarmTime, true);
119    }
120
121    private static void scheduleAlarmHelper(Context context, AlarmManagerInterface manager,
122            long alarmTime, boolean quietUpdate) {
123        int alarmType = AlarmManager.RTC_WAKEUP;
124        Intent intent = new Intent(AlertReceiver.EVENT_REMINDER_APP_ACTION);
125        intent.setClass(context, AlertReceiver.class);
126        if (quietUpdate) {
127            alarmType = AlarmManager.RTC;
128        } else {
129            // Set data field so we get a unique PendingIntent instance per alarm or else alarms
130            // may be dropped.
131            Uri.Builder builder = CalendarAlerts.CONTENT_URI.buildUpon();
132            ContentUris.appendId(builder, alarmTime);
133            intent.setData(builder.build());
134        }
135
136        intent.putExtra(CalendarContract.CalendarAlerts.ALARM_TIME, alarmTime);
137        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
138                PendingIntent.FLAG_UPDATE_CURRENT);
139        manager.set(alarmType, alarmTime, pi);
140    }
141
142    /**
143     * Format the second line which shows time and location for single alert or the
144     * number of events for multiple alerts
145     *     1) Show time only for non-all day events
146     *     2) No date for today
147     *     3) Show "tomorrow" for tomorrow
148     *     4) Show date for days beyond that
149     */
150    static String formatTimeLocation(Context context, long startMillis, boolean allDay,
151            String location) {
152        String tz = Utils.getTimeZone(context, null);
153        Time time = new Time(tz);
154        time.setToNow();
155        int today = Time.getJulianDay(time.toMillis(false), time.gmtoff);
156        time.set(startMillis);
157        int eventDay = Time.getJulianDay(time.toMillis(false), allDay ? 0 : time.gmtoff);
158
159        int flags = DateUtils.FORMAT_ABBREV_ALL;
160        if (!allDay) {
161            flags |= DateUtils.FORMAT_SHOW_TIME;
162            if (DateFormat.is24HourFormat(context)) {
163                flags |= DateUtils.FORMAT_24HOUR;
164            }
165        } else {
166            flags |= DateUtils.FORMAT_UTC;
167        }
168
169        if (eventDay < today || eventDay > today + 1) {
170            flags |= DateUtils.FORMAT_SHOW_DATE;
171        }
172
173        StringBuilder sb = new StringBuilder(Utils.formatDateRange(context, startMillis,
174                startMillis, flags));
175
176        if (!allDay && tz != Time.getCurrentTimezone()) {
177            // Assumes time was set to the current tz
178            time.set(startMillis);
179            boolean isDST = time.isDst != 0;
180            sb.append(" ").append(TimeZone.getTimeZone(tz).getDisplayName(
181                    isDST, TimeZone.SHORT, Locale.getDefault()));
182        }
183
184        if (eventDay == today + 1) {
185            // Tomorrow
186            sb.append(", ");
187            sb.append(context.getString(R.string.tomorrow));
188        }
189
190        String loc;
191        if (location != null && !TextUtils.isEmpty(loc = location.trim())) {
192            sb.append(", ");
193            sb.append(loc);
194        }
195        return sb.toString();
196    }
197
198    public static ContentValues makeContentValues(long eventId, long begin, long end,
199            long alarmTime, int minutes) {
200        ContentValues values = new ContentValues();
201        values.put(CalendarAlerts.EVENT_ID, eventId);
202        values.put(CalendarAlerts.BEGIN, begin);
203        values.put(CalendarAlerts.END, end);
204        values.put(CalendarAlerts.ALARM_TIME, alarmTime);
205        long currentTime = System.currentTimeMillis();
206        values.put(CalendarAlerts.CREATION_TIME, currentTime);
207        values.put(CalendarAlerts.RECEIVED_TIME, 0);
208        values.put(CalendarAlerts.NOTIFY_TIME, 0);
209        values.put(CalendarAlerts.STATE, CalendarAlerts.STATE_SCHEDULED);
210        values.put(CalendarAlerts.MINUTES, minutes);
211        return values;
212    }
213
214    public static Intent buildEventViewIntent(Context c, long eventId, long begin, long end) {
215        Intent i = new Intent(Intent.ACTION_VIEW);
216        Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
217        builder.appendEncodedPath("events/" + eventId);
218        i.setData(builder.build());
219        i.setClass(c, EventInfoActivity.class);
220        i.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, begin);
221        i.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
222        return i;
223    }
224
225    public static SharedPreferences getFiredAlertsTable(Context context) {
226        return context.getSharedPreferences(ALERTS_SHARED_PREFS_NAME, Context.MODE_PRIVATE);
227    }
228
229    private static String getFiredAlertsKey(long eventId, long beginTime,
230            long alarmTime) {
231        StringBuilder sb = new StringBuilder(KEY_FIRED_ALERT_PREFIX);
232        sb.append(eventId);
233        sb.append("_");
234        sb.append(beginTime);
235        sb.append("_");
236        sb.append(alarmTime);
237        return sb.toString();
238    }
239
240    /**
241     * Returns whether the SharedPrefs storage indicates we have fired the alert before.
242     */
243    static boolean hasAlertFiredInSharedPrefs(Context context, long eventId, long beginTime,
244            long alarmTime) {
245        SharedPreferences prefs = getFiredAlertsTable(context);
246        return prefs.contains(getFiredAlertsKey(eventId, beginTime, alarmTime));
247    }
248
249    /**
250     * Store fired alert info in the SharedPrefs.
251     */
252    static void setAlertFiredInSharedPrefs(Context context, long eventId, long beginTime,
253            long alarmTime) {
254        // Store alarm time as the value too so we don't have to parse all the keys to flush
255        // old alarms out of the table later.
256        SharedPreferences prefs = getFiredAlertsTable(context);
257        SharedPreferences.Editor editor = prefs.edit();
258        editor.putLong(getFiredAlertsKey(eventId, beginTime, alarmTime), alarmTime);
259        editor.apply();
260    }
261
262    /**
263     * Scans and flushes the internal storage of old alerts.  Looks up the previous flush
264     * time in SharedPrefs, and performs the flush if overdue.  Otherwise, no-op.
265     */
266    static void flushOldAlertsFromInternalStorage(Context context) {
267        if (BYPASS_DB) {
268            SharedPreferences prefs = getFiredAlertsTable(context);
269
270            // Only flush if it hasn't been done in a while.
271            long nowTime = System.currentTimeMillis();
272            long lastFlushTimeMs = prefs.getLong(KEY_LAST_FLUSH_TIME_MS, 0);
273            if (nowTime - lastFlushTimeMs > FLUSH_INTERVAL_MS) {
274                if (DEBUG) {
275                    Log.d(TAG, "Flushing old alerts from shared prefs table");
276                }
277
278                // Scan through all fired alert entries, removing old ones.
279                SharedPreferences.Editor editor = prefs.edit();
280                Time timeObj = new Time();
281                for (Map.Entry<String, ?> entry : prefs.getAll().entrySet()) {
282                    String key = entry.getKey();
283                    Object value = entry.getValue();
284                    if (key.startsWith(KEY_FIRED_ALERT_PREFIX)) {
285                        long alertTime;
286                        if (value instanceof Long) {
287                            alertTime = (Long) value;
288                        } else {
289                            // Should never occur.
290                            Log.e(TAG,"SharedPrefs key " + key + " did not have Long value: " +
291                                    value);
292                            continue;
293                        }
294
295                        if (nowTime - alertTime >= FLUSH_INTERVAL_MS) {
296                            editor.remove(key);
297                            if (DEBUG) {
298                                int ageInDays = getIntervalInDays(alertTime, nowTime, timeObj);
299                                Log.d(TAG, "SharedPrefs key " + key + ": removed (" + ageInDays +
300                                        " days old)");
301                            }
302                        } else {
303                            if (DEBUG) {
304                                int ageInDays = getIntervalInDays(alertTime, nowTime, timeObj);
305                                Log.d(TAG, "SharedPrefs key " + key + ": keep (" + ageInDays +
306                                        " days old)");
307                            }
308                        }
309                    }
310                }
311                editor.putLong(KEY_LAST_FLUSH_TIME_MS, nowTime);
312                editor.apply();
313            }
314        }
315    }
316
317    private static int getIntervalInDays(long startMillis, long endMillis, Time timeObj) {
318        timeObj.set(startMillis);
319        int startDay = Time.getJulianDay(startMillis, timeObj.gmtoff);
320        timeObj.set(endMillis);
321        return Time.getJulianDay(endMillis, timeObj.gmtoff) - startDay;
322    }
323}
324