OSDN Git Service

Moving alarm creation into SetAlarm.
[android-x86/packages-apps-DeskClock.git] / src / com / android / deskclock / Alarms.java
1 /*
2  * Copyright (C) 2007 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
17 package com.android.deskclock;
18
19 import android.app.AlarmManager;
20 import android.app.NotificationManager;
21 import android.app.PendingIntent;
22 import android.content.ContentResolver;
23 import android.content.ContentValues;
24 import android.content.ContentUris;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.database.Cursor;
29 import android.net.Uri;
30 import android.os.Parcel;
31 import android.provider.Settings;
32 import android.text.format.DateFormat;
33
34 import java.util.Calendar;
35 import java.text.DateFormatSymbols;
36
37 /**
38  * The Alarms provider supplies info about Alarm Clock settings
39  */
40 public class Alarms {
41
42     // This action triggers the AlarmReceiver as well as the AlarmKlaxon. It
43     // is a public action used in the manifest for receiving Alarm broadcasts
44     // from the alarm manager.
45     public static final String ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT";
46
47     // This is a private action used by the AlarmKlaxon to update the UI to
48     // show the alarm has been killed.
49     public static final String ALARM_KILLED = "alarm_killed";
50
51     // Extra in the ALARM_KILLED intent to indicate to the user how long the
52     // alarm played before being killed.
53     public static final String ALARM_KILLED_TIMEOUT = "alarm_killed_timeout";
54
55     // This string is used to indicate a silent alarm in the db.
56     public static final String ALARM_ALERT_SILENT = "silent";
57
58     // This intent is sent from the notification when the user cancels the
59     // snooze alert.
60     public static final String CANCEL_SNOOZE = "cancel_snooze";
61
62     // This string is used when passing an Alarm object through an intent.
63     public static final String ALARM_INTENT_EXTRA = "intent.extra.alarm";
64
65     // This extra is the raw Alarm object data. It is used in the
66     // AlarmManagerService to avoid a ClassNotFoundException when filling in
67     // the Intent extras.
68     public static final String ALARM_RAW_DATA = "intent.extra.alarm_raw";
69
70     // This string is used to identify the alarm id passed to SetAlarm from the
71     // list of alarms.
72     public static final String ALARM_ID = "alarm_id";
73
74     final static String PREF_SNOOZE_ID = "snooze_id";
75     final static String PREF_SNOOZE_TIME = "snooze_time";
76
77     private final static String DM12 = "E h:mm aa";
78     private final static String DM24 = "E k:mm";
79
80     private final static String M12 = "h:mm aa";
81     // Shared with DigitalClock
82     final static String M24 = "kk:mm";
83
84     /**
85      * Creates a new Alarm.
86      */
87     public static long addAlarm(Context context, Alarm alarm) {
88         ContentValues values = createContentValues(alarm);
89         context.getContentResolver().insert(Alarm.Columns.CONTENT_URI, values);
90
91         long timeInMillis = calculateAlarm(alarm);
92         if (alarm.enabled) {
93             clearSnoozeIfNeeded(context, timeInMillis);
94         }
95         setNextAlert(context);
96         return timeInMillis;
97     }
98
99     /**
100      * Removes an existing Alarm.  If this alarm is snoozing, disables
101      * snooze.  Sets next alert.
102      */
103     public static void deleteAlarm(
104             Context context, int alarmId) {
105
106         ContentResolver contentResolver = context.getContentResolver();
107         /* If alarm is snoozing, lose it */
108         disableSnoozeAlert(context, alarmId);
109
110         Uri uri = ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarmId);
111         contentResolver.delete(uri, "", null);
112
113         setNextAlert(context);
114     }
115
116     /**
117      * Queries all alarms
118      * @return cursor over all alarms
119      */
120     public static Cursor getAlarmsCursor(ContentResolver contentResolver) {
121         return contentResolver.query(
122                 Alarm.Columns.CONTENT_URI, Alarm.Columns.ALARM_QUERY_COLUMNS,
123                 null, null, Alarm.Columns.DEFAULT_SORT_ORDER);
124     }
125
126     // Private method to get a more limited set of alarms from the database.
127     private static Cursor getFilteredAlarmsCursor(
128             ContentResolver contentResolver) {
129         return contentResolver.query(Alarm.Columns.CONTENT_URI,
130                 Alarm.Columns.ALARM_QUERY_COLUMNS, Alarm.Columns.WHERE_ENABLED,
131                 null, null);
132     }
133
134     private static ContentValues createContentValues(Alarm alarm) {
135         ContentValues values = new ContentValues(8);
136         // Set the alarm_time value if this alarm does not repeat. This will be
137         // used later to disable expire alarms.
138         long time = 0;
139         if (!alarm.daysOfWeek.isRepeatSet()) {
140             time = calculateAlarm(alarm);
141         }
142
143         values.put(Alarm.Columns.ENABLED, alarm.enabled ? 1 : 0);
144         values.put(Alarm.Columns.HOUR, alarm.hour);
145         values.put(Alarm.Columns.MINUTES, alarm.minutes);
146         values.put(Alarm.Columns.ALARM_TIME, alarm.time);
147         values.put(Alarm.Columns.DAYS_OF_WEEK, alarm.daysOfWeek.getCoded());
148         values.put(Alarm.Columns.VIBRATE, alarm.vibrate);
149         values.put(Alarm.Columns.MESSAGE, alarm.label);
150
151         // A null alert Uri indicates a silent alarm.
152         values.put(Alarm.Columns.ALERT, alarm.alert == null ? ALARM_ALERT_SILENT
153                 : alarm.alert.toString());
154
155         return values;
156     }
157
158     private static void clearSnoozeIfNeeded(Context context, long alarmTime) {
159         // If this alarm fires before the next snooze, clear the snooze to
160         // enable this alarm.
161         SharedPreferences prefs =
162                 context.getSharedPreferences(AlarmClock.PREFERENCES, 0);
163         long snoozeTime = prefs.getLong(PREF_SNOOZE_TIME, 0);
164         if (alarmTime < snoozeTime) {
165             clearSnoozePreference(context, prefs);
166         }
167     }
168
169     /**
170      * Return an Alarm object representing the alarm id in the database.
171      * Returns null if no alarm exists.
172      */
173     public static Alarm getAlarm(ContentResolver contentResolver, int alarmId) {
174         Cursor cursor = contentResolver.query(
175                 ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarmId),
176                 Alarm.Columns.ALARM_QUERY_COLUMNS,
177                 null, null, null);
178         Alarm alarm = null;
179         if (cursor != null) {
180             if (cursor.moveToFirst()) {
181                 alarm = new Alarm(cursor);
182             }
183             cursor.close();
184         }
185         return alarm;
186     }
187
188
189     /**
190      * A convenience method to set an alarm in the Alarms
191      * content provider.
192      * @return Time when the alarm will fire.
193      */
194     public static long setAlarm(Context context, Alarm alarm) {
195         ContentValues values = createContentValues(alarm);
196         ContentResolver resolver = context.getContentResolver();
197         resolver.update(
198                 ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarm.id),
199                 values, null, null);
200
201         long timeInMillis = calculateAlarm(alarm);
202
203         if (alarm.enabled) {
204             clearSnoozeIfNeeded(context, timeInMillis);
205         }
206
207         setNextAlert(context);
208
209         return timeInMillis;
210     }
211
212     /**
213      * A convenience method to enable or disable an alarm.
214      *
215      * @param id             corresponds to the _id column
216      * @param enabled        corresponds to the ENABLED column
217      */
218
219     public static void enableAlarm(
220             final Context context, final int id, boolean enabled) {
221         enableAlarmInternal(context, id, enabled);
222         setNextAlert(context);
223     }
224
225     private static void enableAlarmInternal(final Context context,
226             final int id, boolean enabled) {
227         enableAlarmInternal(context, getAlarm(context.getContentResolver(), id),
228                 enabled);
229     }
230
231     private static void enableAlarmInternal(final Context context,
232             final Alarm alarm, boolean enabled) {
233         if (alarm == null) {
234             return;
235         }
236         ContentResolver resolver = context.getContentResolver();
237
238         ContentValues values = new ContentValues(2);
239         values.put(Alarm.Columns.ENABLED, enabled ? 1 : 0);
240
241         // If we are enabling the alarm, calculate alarm time since the time
242         // value in Alarm may be old.
243         if (enabled) {
244             long time = 0;
245             if (!alarm.daysOfWeek.isRepeatSet()) {
246                 time = calculateAlarm(alarm);
247             }
248             values.put(Alarm.Columns.ALARM_TIME, time);
249         } else {
250             // Clear the snooze if the id matches.
251             disableSnoozeAlert(context, alarm.id);
252         }
253
254         resolver.update(ContentUris.withAppendedId(
255                 Alarm.Columns.CONTENT_URI, alarm.id), values, null, null);
256     }
257
258     public static Alarm calculateNextAlert(final Context context) {
259         Alarm alarm = null;
260         long minTime = Long.MAX_VALUE;
261         long now = System.currentTimeMillis();
262         Cursor cursor = getFilteredAlarmsCursor(context.getContentResolver());
263         if (cursor != null) {
264             if (cursor.moveToFirst()) {
265                 do {
266                     Alarm a = new Alarm(cursor);
267                     // A time of 0 indicates this is a repeating alarm, so
268                     // calculate the time to get the next alert.
269                     if (a.time == 0) {
270                         a.time = calculateAlarm(a);
271                     } else if (a.time < now) {
272                         // Expired alarm, disable it and move along.
273                         enableAlarmInternal(context, a, false);
274                         continue;
275                     }
276                     if (a.time < minTime) {
277                         minTime = a.time;
278                         alarm = a;
279                     }
280                 } while (cursor.moveToNext());
281             }
282             cursor.close();
283         }
284         return alarm;
285     }
286
287     /**
288      * Disables non-repeating alarms that have passed.  Called at
289      * boot.
290      */
291     public static void disableExpiredAlarms(final Context context) {
292         Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
293         long now = System.currentTimeMillis();
294
295         if (cur.moveToFirst()) {
296             do {
297                 Alarm alarm = new Alarm(cur);
298                 // A time of 0 means this alarm repeats. If the time is
299                 // non-zero, check if the time is before now.
300                 if (alarm.time != 0 && alarm.time < now) {
301                     if (Log.LOGV) {
302                         Log.v("** DISABLE " + alarm.id + " now " + now +" set "
303                                 + alarm.time);
304                     }
305                     enableAlarmInternal(context, alarm, false);
306                 }
307             } while (cur.moveToNext());
308         }
309         cur.close();
310     }
311
312     /**
313      * Called at system startup, on time/timezone change, and whenever
314      * the user changes alarm settings.  Activates snooze if set,
315      * otherwise loads all alarms, activates next alert.
316      */
317     public static void setNextAlert(final Context context) {
318         if (!enableSnoozeAlert(context)) {
319             Alarm alarm = calculateNextAlert(context);
320             if (alarm != null) {
321                 enableAlert(context, alarm, alarm.time);
322             } else {
323                 disableAlert(context);
324             }
325         }
326     }
327
328     /**
329      * Sets alert in AlarmManger and StatusBar.  This is what will
330      * actually launch the alert when the alarm triggers.
331      *
332      * @param alarm Alarm.
333      * @param atTimeInMillis milliseconds since epoch
334      */
335     private static void enableAlert(Context context, final Alarm alarm,
336             final long atTimeInMillis) {
337         AlarmManager am = (AlarmManager)
338                 context.getSystemService(Context.ALARM_SERVICE);
339
340         if (Log.LOGV) {
341             Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
342         }
343
344         Intent intent = new Intent(ALARM_ALERT_ACTION);
345
346         // XXX: This is a slight hack to avoid an exception in the remote
347         // AlarmManagerService process. The AlarmManager adds extra data to
348         // this Intent which causes it to inflate. Since the remote process
349         // does not know about the Alarm class, it throws a
350         // ClassNotFoundException.
351         //
352         // To avoid this, we marshall the data ourselves and then parcel a plain
353         // byte[] array. The AlarmReceiver class knows to build the Alarm
354         // object from the byte[] array.
355         Parcel out = Parcel.obtain();
356         alarm.writeToParcel(out, 0);
357         out.setDataPosition(0);
358         intent.putExtra(ALARM_RAW_DATA, out.marshall());
359
360         PendingIntent sender = PendingIntent.getBroadcast(
361                 context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
362
363         am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
364
365         setStatusBarIcon(context, true);
366
367         Calendar c = Calendar.getInstance();
368         c.setTimeInMillis(atTimeInMillis);
369         String timeString = formatDayAndTime(context, c);
370         saveNextAlarm(context, timeString);
371     }
372
373     /**
374      * Disables alert in AlarmManger and StatusBar.
375      *
376      * @param id Alarm ID.
377      */
378     static void disableAlert(Context context) {
379         AlarmManager am = (AlarmManager)
380                 context.getSystemService(Context.ALARM_SERVICE);
381         PendingIntent sender = PendingIntent.getBroadcast(
382                 context, 0, new Intent(ALARM_ALERT_ACTION),
383                 PendingIntent.FLAG_CANCEL_CURRENT);
384         am.cancel(sender);
385         setStatusBarIcon(context, false);
386         saveNextAlarm(context, "");
387     }
388
389     static void saveSnoozeAlert(final Context context, final int id,
390             final long time) {
391         SharedPreferences prefs = context.getSharedPreferences(
392                 AlarmClock.PREFERENCES, 0);
393         if (id == -1) {
394             clearSnoozePreference(context, prefs);
395         } else {
396             SharedPreferences.Editor ed = prefs.edit();
397             ed.putInt(PREF_SNOOZE_ID, id);
398             ed.putLong(PREF_SNOOZE_TIME, time);
399             ed.commit();
400         }
401         // Set the next alert after updating the snooze.
402         setNextAlert(context);
403     }
404
405     /**
406      * Disable the snooze alert if the given id matches the snooze id.
407      */
408     static void disableSnoozeAlert(final Context context, final int id) {
409         SharedPreferences prefs = context.getSharedPreferences(
410                 AlarmClock.PREFERENCES, 0);
411         int snoozeId = prefs.getInt(PREF_SNOOZE_ID, -1);
412         if (snoozeId == -1) {
413             // No snooze set, do nothing.
414             return;
415         } else if (snoozeId == id) {
416             // This is the same id so clear the shared prefs.
417             clearSnoozePreference(context, prefs);
418         }
419     }
420
421     // Helper to remove the snooze preference. Do not use clear because that
422     // will erase the clock preferences. Also clear the snooze notification in
423     // the window shade.
424     private static void clearSnoozePreference(final Context context,
425             final SharedPreferences prefs) {
426         final int alarmId = prefs.getInt(PREF_SNOOZE_ID, -1);
427         if (alarmId != -1) {
428             NotificationManager nm = (NotificationManager)
429                     context.getSystemService(Context.NOTIFICATION_SERVICE);
430             nm.cancel(alarmId);
431         }
432
433         final SharedPreferences.Editor ed = prefs.edit();
434         ed.remove(PREF_SNOOZE_ID);
435         ed.remove(PREF_SNOOZE_TIME);
436         ed.commit();
437     };
438
439     /**
440      * If there is a snooze set, enable it in AlarmManager
441      * @return true if snooze is set
442      */
443     private static boolean enableSnoozeAlert(final Context context) {
444         SharedPreferences prefs = context.getSharedPreferences(
445                 AlarmClock.PREFERENCES, 0);
446
447         int id = prefs.getInt(PREF_SNOOZE_ID, -1);
448         if (id == -1) {
449             return false;
450         }
451         long time = prefs.getLong(PREF_SNOOZE_TIME, -1);
452
453         // Get the alarm from the db.
454         final Alarm alarm = getAlarm(context.getContentResolver(), id);
455         if (alarm == null) {
456             return false;
457         }
458         // The time in the database is either 0 (repeating) or a specific time
459         // for a non-repeating alarm. Update this value so the AlarmReceiver
460         // has the right time to compare.
461         alarm.time = time;
462
463         enableAlert(context, alarm, time);
464         return true;
465     }
466
467     /**
468      * Tells the StatusBar whether the alarm is enabled or disabled
469      */
470     private static void setStatusBarIcon(Context context, boolean enabled) {
471         Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
472         alarmChanged.putExtra("alarmSet", enabled);
473         context.sendBroadcast(alarmChanged);
474     }
475
476     private static long calculateAlarm(Alarm alarm) {
477         return calculateAlarm(alarm.hour, alarm.minutes, alarm.daysOfWeek)
478                 .getTimeInMillis();
479     }
480
481     /**
482      * Given an alarm in hours and minutes, return a time suitable for
483      * setting in AlarmManager.
484      */
485     static Calendar calculateAlarm(int hour, int minute,
486             Alarm.DaysOfWeek daysOfWeek) {
487
488         // start with now
489         Calendar c = Calendar.getInstance();
490         c.setTimeInMillis(System.currentTimeMillis());
491
492         int nowHour = c.get(Calendar.HOUR_OF_DAY);
493         int nowMinute = c.get(Calendar.MINUTE);
494
495         // if alarm is behind current time, advance one day
496         if (hour < nowHour  ||
497             hour == nowHour && minute <= nowMinute) {
498             c.add(Calendar.DAY_OF_YEAR, 1);
499         }
500         c.set(Calendar.HOUR_OF_DAY, hour);
501         c.set(Calendar.MINUTE, minute);
502         c.set(Calendar.SECOND, 0);
503         c.set(Calendar.MILLISECOND, 0);
504
505         int addDays = daysOfWeek.getNextAlarm(c);
506         if (addDays > 0) c.add(Calendar.DAY_OF_WEEK, addDays);
507         return c;
508     }
509
510     static String formatTime(final Context context, int hour, int minute,
511                              Alarm.DaysOfWeek daysOfWeek) {
512         Calendar c = calculateAlarm(hour, minute, daysOfWeek);
513         return formatTime(context, c);
514     }
515
516     /* used by AlarmAlert */
517     static String formatTime(final Context context, Calendar c) {
518         String format = get24HourMode(context) ? M24 : M12;
519         return (c == null) ? "" : (String)DateFormat.format(format, c);
520     }
521
522     /**
523      * Shows day and time -- used for lock screen
524      */
525     private static String formatDayAndTime(final Context context, Calendar c) {
526         String format = get24HourMode(context) ? DM24 : DM12;
527         return (c == null) ? "" : (String)DateFormat.format(format, c);
528     }
529
530     /**
531      * Save time of the next alarm, as a formatted string, into the system
532      * settings so those who care can make use of it.
533      */
534     static void saveNextAlarm(final Context context, String timeString) {
535         Settings.System.putString(context.getContentResolver(),
536                                   Settings.System.NEXT_ALARM_FORMATTED,
537                                   timeString);
538     }
539
540     /**
541      * @return true if clock is set to 24-hour mode
542      */
543     static boolean get24HourMode(final Context context) {
544         return android.text.format.DateFormat.is24HourFormat(context);
545     }
546 }