2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.deskclock;
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;
34 import java.util.Calendar;
35 import java.text.DateFormatSymbols;
38 * The Alarms provider supplies info about Alarm Clock settings
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";
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";
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";
55 // This string is used to indicate a silent alarm in the db.
56 public static final String ALARM_ALERT_SILENT = "silent";
58 // This intent is sent from the notification when the user cancels the
60 public static final String CANCEL_SNOOZE = "cancel_snooze";
62 // This string is used when passing an Alarm object through an intent.
63 public static final String ALARM_INTENT_EXTRA = "intent.extra.alarm";
65 // This extra is the raw Alarm object data. It is used in the
66 // AlarmManagerService to avoid a ClassNotFoundException when filling in
68 public static final String ALARM_RAW_DATA = "intent.extra.alarm_raw";
70 // This string is used to identify the alarm id passed to SetAlarm from the
72 public static final String ALARM_ID = "alarm_id";
74 final static String PREF_SNOOZE_ID = "snooze_id";
75 final static String PREF_SNOOZE_TIME = "snooze_time";
77 private final static String DM12 = "E h:mm aa";
78 private final static String DM24 = "E k:mm";
80 private final static String M12 = "h:mm aa";
81 // Shared with DigitalClock
82 final static String M24 = "kk:mm";
85 * Creates a new Alarm.
87 public static long addAlarm(Context context, Alarm alarm) {
88 ContentValues values = createContentValues(alarm);
89 context.getContentResolver().insert(Alarm.Columns.CONTENT_URI, values);
91 long timeInMillis = calculateAlarm(alarm);
93 clearSnoozeIfNeeded(context, timeInMillis);
95 setNextAlert(context);
100 * Removes an existing Alarm. If this alarm is snoozing, disables
101 * snooze. Sets next alert.
103 public static void deleteAlarm(
104 Context context, int alarmId) {
106 ContentResolver contentResolver = context.getContentResolver();
107 /* If alarm is snoozing, lose it */
108 disableSnoozeAlert(context, alarmId);
110 Uri uri = ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarmId);
111 contentResolver.delete(uri, "", null);
113 setNextAlert(context);
118 * @return cursor over all alarms
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);
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,
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.
139 if (!alarm.daysOfWeek.isRepeatSet()) {
140 time = calculateAlarm(alarm);
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);
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());
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);
170 * Return an Alarm object representing the alarm id in the database.
171 * Returns null if no alarm exists.
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,
179 if (cursor != null) {
180 if (cursor.moveToFirst()) {
181 alarm = new Alarm(cursor);
190 * A convenience method to set an alarm in the Alarms
192 * @return Time when the alarm will fire.
194 public static long setAlarm(Context context, Alarm alarm) {
195 ContentValues values = createContentValues(alarm);
196 ContentResolver resolver = context.getContentResolver();
198 ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarm.id),
201 long timeInMillis = calculateAlarm(alarm);
204 clearSnoozeIfNeeded(context, timeInMillis);
207 setNextAlert(context);
213 * A convenience method to enable or disable an alarm.
215 * @param id corresponds to the _id column
216 * @param enabled corresponds to the ENABLED column
219 public static void enableAlarm(
220 final Context context, final int id, boolean enabled) {
221 enableAlarmInternal(context, id, enabled);
222 setNextAlert(context);
225 private static void enableAlarmInternal(final Context context,
226 final int id, boolean enabled) {
227 enableAlarmInternal(context, getAlarm(context.getContentResolver(), id),
231 private static void enableAlarmInternal(final Context context,
232 final Alarm alarm, boolean enabled) {
236 ContentResolver resolver = context.getContentResolver();
238 ContentValues values = new ContentValues(2);
239 values.put(Alarm.Columns.ENABLED, enabled ? 1 : 0);
241 // If we are enabling the alarm, calculate alarm time since the time
242 // value in Alarm may be old.
245 if (!alarm.daysOfWeek.isRepeatSet()) {
246 time = calculateAlarm(alarm);
248 values.put(Alarm.Columns.ALARM_TIME, time);
250 // Clear the snooze if the id matches.
251 disableSnoozeAlert(context, alarm.id);
254 resolver.update(ContentUris.withAppendedId(
255 Alarm.Columns.CONTENT_URI, alarm.id), values, null, null);
258 public static Alarm calculateNextAlert(final Context context) {
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()) {
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.
270 a.time = calculateAlarm(a);
271 } else if (a.time < now) {
272 // Expired alarm, disable it and move along.
273 enableAlarmInternal(context, a, false);
276 if (a.time < minTime) {
280 } while (cursor.moveToNext());
288 * Disables non-repeating alarms that have passed. Called at
291 public static void disableExpiredAlarms(final Context context) {
292 Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
293 long now = System.currentTimeMillis();
295 if (cur.moveToFirst()) {
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) {
302 Log.v("** DISABLE " + alarm.id + " now " + now +" set "
305 enableAlarmInternal(context, alarm, false);
307 } while (cur.moveToNext());
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.
317 public static void setNextAlert(final Context context) {
318 if (!enableSnoozeAlert(context)) {
319 Alarm alarm = calculateNextAlert(context);
321 enableAlert(context, alarm, alarm.time);
323 disableAlert(context);
329 * Sets alert in AlarmManger and StatusBar. This is what will
330 * actually launch the alert when the alarm triggers.
332 * @param alarm Alarm.
333 * @param atTimeInMillis milliseconds since epoch
335 private static void enableAlert(Context context, final Alarm alarm,
336 final long atTimeInMillis) {
337 AlarmManager am = (AlarmManager)
338 context.getSystemService(Context.ALARM_SERVICE);
341 Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
344 Intent intent = new Intent(ALARM_ALERT_ACTION);
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.
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());
360 PendingIntent sender = PendingIntent.getBroadcast(
361 context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
363 am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
365 setStatusBarIcon(context, true);
367 Calendar c = Calendar.getInstance();
368 c.setTimeInMillis(atTimeInMillis);
369 String timeString = formatDayAndTime(context, c);
370 saveNextAlarm(context, timeString);
374 * Disables alert in AlarmManger and StatusBar.
376 * @param id Alarm ID.
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);
385 setStatusBarIcon(context, false);
386 saveNextAlarm(context, "");
389 static void saveSnoozeAlert(final Context context, final int id,
391 SharedPreferences prefs = context.getSharedPreferences(
392 AlarmClock.PREFERENCES, 0);
394 clearSnoozePreference(context, prefs);
396 SharedPreferences.Editor ed = prefs.edit();
397 ed.putInt(PREF_SNOOZE_ID, id);
398 ed.putLong(PREF_SNOOZE_TIME, time);
401 // Set the next alert after updating the snooze.
402 setNextAlert(context);
406 * Disable the snooze alert if the given id matches the snooze id.
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.
415 } else if (snoozeId == id) {
416 // This is the same id so clear the shared prefs.
417 clearSnoozePreference(context, prefs);
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
424 private static void clearSnoozePreference(final Context context,
425 final SharedPreferences prefs) {
426 final int alarmId = prefs.getInt(PREF_SNOOZE_ID, -1);
428 NotificationManager nm = (NotificationManager)
429 context.getSystemService(Context.NOTIFICATION_SERVICE);
433 final SharedPreferences.Editor ed = prefs.edit();
434 ed.remove(PREF_SNOOZE_ID);
435 ed.remove(PREF_SNOOZE_TIME);
440 * If there is a snooze set, enable it in AlarmManager
441 * @return true if snooze is set
443 private static boolean enableSnoozeAlert(final Context context) {
444 SharedPreferences prefs = context.getSharedPreferences(
445 AlarmClock.PREFERENCES, 0);
447 int id = prefs.getInt(PREF_SNOOZE_ID, -1);
451 long time = prefs.getLong(PREF_SNOOZE_TIME, -1);
453 // Get the alarm from the db.
454 final Alarm alarm = getAlarm(context.getContentResolver(), id);
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.
463 enableAlert(context, alarm, time);
468 * Tells the StatusBar whether the alarm is enabled or disabled
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);
476 private static long calculateAlarm(Alarm alarm) {
477 return calculateAlarm(alarm.hour, alarm.minutes, alarm.daysOfWeek)
482 * Given an alarm in hours and minutes, return a time suitable for
483 * setting in AlarmManager.
485 static Calendar calculateAlarm(int hour, int minute,
486 Alarm.DaysOfWeek daysOfWeek) {
489 Calendar c = Calendar.getInstance();
490 c.setTimeInMillis(System.currentTimeMillis());
492 int nowHour = c.get(Calendar.HOUR_OF_DAY);
493 int nowMinute = c.get(Calendar.MINUTE);
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);
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);
505 int addDays = daysOfWeek.getNextAlarm(c);
506 if (addDays > 0) c.add(Calendar.DAY_OF_WEEK, addDays);
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);
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);
523 * Shows day and time -- used for lock screen
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);
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.
534 static void saveNextAlarm(final Context context, String timeString) {
535 Settings.System.putString(context.getContentResolver(),
536 Settings.System.NEXT_ALARM_FORMATTED,
541 * @return true if clock is set to 24-hour mode
543 static boolean get24HourMode(final Context context) {
544 return android.text.format.DateFormat.is24HourFormat(context);