• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 android.app;
18 
19 import android.content.Context;
20 import android.content.Intent;
21 import android.os.Build;
22 import android.os.RemoteException;
23 import android.os.WorkSource;
24 
25 /**
26  * This class provides access to the system alarm services.  These allow you
27  * to schedule your application to be run at some point in the future.  When
28  * an alarm goes off, the {@link Intent} that had been registered for it
29  * is broadcast by the system, automatically starting the target application
30  * if it is not already running.  Registered alarms are retained while the
31  * device is asleep (and can optionally wake the device up if they go off
32  * during that time), but will be cleared if it is turned off and rebooted.
33  *
34  * <p>The Alarm Manager holds a CPU wake lock as long as the alarm receiver's
35  * onReceive() method is executing. This guarantees that the phone will not sleep
36  * until you have finished handling the broadcast. Once onReceive() returns, the
37  * Alarm Manager releases this wake lock. This means that the phone will in some
38  * cases sleep as soon as your onReceive() method completes.  If your alarm receiver
39  * called {@link android.content.Context#startService Context.startService()}, it
40  * is possible that the phone will sleep before the requested service is launched.
41  * To prevent this, your BroadcastReceiver and Service will need to implement a
42  * separate wake lock policy to ensure that the phone continues running until the
43  * service becomes available.
44  *
45  * <p><b>Note: The Alarm Manager is intended for cases where you want to have
46  * your application code run at a specific time, even if your application is
47  * not currently running.  For normal timing operations (ticks, timeouts,
48  * etc) it is easier and much more efficient to use
49  * {@link android.os.Handler}.</b>
50  *
51  * <p class="caution"><strong>Note:</strong> Beginning with API 19
52  * ({@link android.os.Build.VERSION_CODES#KITKAT}) alarm delivery is inexact:
53  * the OS will shift alarms in order to minimize wakeups and battery use.  There are
54  * new APIs to support applications which need strict delivery guarantees; see
55  * {@link #setWindow(int, long, long, PendingIntent)} and
56  * {@link #setExact(int, long, PendingIntent)}.  Applications whose {@code targetSdkVersion}
57  * is earlier than API 19 will continue to see the previous behavior in which all
58  * alarms are delivered exactly when requested.
59  *
60  * <p>You do not
61  * instantiate this class directly; instead, retrieve it through
62  * {@link android.content.Context#getSystemService
63  * Context.getSystemService(Context.ALARM_SERVICE)}.
64  */
65 public class AlarmManager
66 {
67     private static final String TAG = "AlarmManager";
68 
69     /**
70      * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
71      * (wall clock time in UTC), which will wake up the device when
72      * it goes off.
73      */
74     public static final int RTC_WAKEUP = 0;
75     /**
76      * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
77      * (wall clock time in UTC).  This alarm does not wake the
78      * device up; if it goes off while the device is asleep, it will not be
79      * delivered until the next time the device wakes up.
80      */
81     public static final int RTC = 1;
82     /**
83      * Alarm time in {@link android.os.SystemClock#elapsedRealtime
84      * SystemClock.elapsedRealtime()} (time since boot, including sleep),
85      * which will wake up the device when it goes off.
86      */
87     public static final int ELAPSED_REALTIME_WAKEUP = 2;
88     /**
89      * Alarm time in {@link android.os.SystemClock#elapsedRealtime
90      * SystemClock.elapsedRealtime()} (time since boot, including sleep).
91      * This alarm does not wake the device up; if it goes off while the device
92      * is asleep, it will not be delivered until the next time the device
93      * wakes up.
94      */
95     public static final int ELAPSED_REALTIME = 3;
96 
97     /** @hide */
98     public static final long WINDOW_EXACT = 0;
99     /** @hide */
100     public static final long WINDOW_HEURISTIC = -1;
101 
102     private final IAlarmManager mService;
103     private final boolean mAlwaysExact;
104 
105 
106     /**
107      * package private on purpose
108      */
AlarmManager(IAlarmManager service, Context ctx)109     AlarmManager(IAlarmManager service, Context ctx) {
110         mService = service;
111 
112         final int sdkVersion = ctx.getApplicationInfo().targetSdkVersion;
113         mAlwaysExact = (sdkVersion < Build.VERSION_CODES.KITKAT);
114     }
115 
legacyExactLength()116     private long legacyExactLength() {
117         return (mAlwaysExact ? WINDOW_EXACT : WINDOW_HEURISTIC);
118     }
119 
120     /**
121      * <p>Schedule an alarm.  <b>Note: for timing operations (ticks, timeouts,
122      * etc) it is easier and much more efficient to use {@link android.os.Handler}.</b>
123      * If there is already an alarm scheduled for the same IntentSender, that previous
124      * alarm will first be canceled.
125      *
126      * <p>If the stated trigger time is in the past, the alarm will be triggered
127      * immediately.  If there is already an alarm for this Intent
128      * scheduled (with the equality of two intents being defined by
129      * {@link Intent#filterEquals}), then it will be removed and replaced by
130      * this one.
131      *
132      * <p>
133      * The alarm is an Intent broadcast that goes to a broadcast receiver that
134      * you registered with {@link android.content.Context#registerReceiver}
135      * or through the &lt;receiver&gt; tag in an AndroidManifest.xml file.
136      *
137      * <p>
138      * Alarm intents are delivered with a data extra of type int called
139      * {@link Intent#EXTRA_ALARM_COUNT Intent.EXTRA_ALARM_COUNT} that indicates
140      * how many past alarm events have been accumulated into this intent
141      * broadcast.  Recurring alarms that have gone undelivered because the
142      * phone was asleep may have a count greater than one when delivered.
143      *
144      * <div class="note">
145      * <p>
146      * <b>Note:</b> Beginning in API 19, the trigger time passed to this method
147      * is treated as inexact: the alarm will not be delivered before this time, but
148      * may be deferred and delivered some time later.  The OS will use
149      * this policy in order to "batch" alarms together across the entire system,
150      * minimizing the number of times the device needs to "wake up" and minimizing
151      * battery use.  In general, alarms scheduled in the near future will not
152      * be deferred as long as alarms scheduled far in the future.
153      *
154      * <p>
155      * With the new batching policy, delivery ordering guarantees are not as
156      * strong as they were previously.  If the application sets multiple alarms,
157      * it is possible that these alarms' <em>actual</em> delivery ordering may not match
158      * the order of their <em>requested</em> delivery times.  If your application has
159      * strong ordering requirements there are other APIs that you can use to get
160      * the necessary behavior; see {@link #setWindow(int, long, long, PendingIntent)}
161      * and {@link #setExact(int, long, PendingIntent)}.
162      *
163      * <p>
164      * Applications whose {@code targetSdkVersion} is before API 19 will
165      * continue to get the previous alarm behavior: all of their scheduled alarms
166      * will be treated as exact.
167      * </div>
168      *
169      * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
170      *        {@link #RTC}, or {@link #RTC_WAKEUP}.
171      * @param triggerAtMillis time in milliseconds that the alarm should go
172      * off, using the appropriate clock (depending on the alarm type).
173      * @param operation Action to perform when the alarm goes off;
174      * typically comes from {@link PendingIntent#getBroadcast
175      * IntentSender.getBroadcast()}.
176      *
177      * @see android.os.Handler
178      * @see #setExact
179      * @see #setRepeating
180      * @see #setWindow
181      * @see #cancel
182      * @see android.content.Context#sendBroadcast
183      * @see android.content.Context#registerReceiver
184      * @see android.content.Intent#filterEquals
185      * @see #ELAPSED_REALTIME
186      * @see #ELAPSED_REALTIME_WAKEUP
187      * @see #RTC
188      * @see #RTC_WAKEUP
189      */
set(int type, long triggerAtMillis, PendingIntent operation)190     public void set(int type, long triggerAtMillis, PendingIntent operation) {
191         setImpl(type, triggerAtMillis, legacyExactLength(), 0, operation, null);
192     }
193 
194     /**
195      * Schedule a repeating alarm.  <b>Note: for timing operations (ticks,
196      * timeouts, etc) it is easier and much more efficient to use
197      * {@link android.os.Handler}.</b>  If there is already an alarm scheduled
198      * for the same IntentSender, it will first be canceled.
199      *
200      * <p>Like {@link #set}, except you can also supply a period at which
201      * the alarm will automatically repeat.  This alarm continues
202      * repeating until explicitly removed with {@link #cancel}.  If the stated
203      * trigger time is in the past, the alarm will be triggered immediately, with an
204      * alarm count depending on how far in the past the trigger time is relative
205      * to the repeat interval.
206      *
207      * <p>If an alarm is delayed (by system sleep, for example, for non
208      * _WAKEUP alarm types), a skipped repeat will be delivered as soon as
209      * possible.  After that, future alarms will be delivered according to the
210      * original schedule; they do not drift over time.  For example, if you have
211      * set a recurring alarm for the top of every hour but the phone was asleep
212      * from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens,
213      * then the next alarm will be sent at 9:00.
214      *
215      * <p>If your application wants to allow the delivery times to drift in
216      * order to guarantee that at least a certain time interval always elapses
217      * between alarms, then the approach to take is to use one-time alarms,
218      * scheduling the next one yourself when handling each alarm delivery.
219      *
220      * <p class="note">
221      * <b>Note:</b> as of API 19, all repeating alarms are inexact.  If your
222      * application needs precise delivery times then it must use one-time
223      * exact alarms, rescheduling each time as described above. Legacy applications
224      * whose {@code targetSdkVersion} is earlier than API 19 will continue to have all
225      * of their alarms, including repeating alarms, treated as exact.
226      *
227      * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
228      *        {@link #RTC}, or {@link #RTC_WAKEUP}.
229      * @param triggerAtMillis time in milliseconds that the alarm should first
230      * go off, using the appropriate clock (depending on the alarm type).
231      * @param intervalMillis interval in milliseconds between subsequent repeats
232      * of the alarm.
233      * @param operation Action to perform when the alarm goes off;
234      * typically comes from {@link PendingIntent#getBroadcast
235      * IntentSender.getBroadcast()}.
236      *
237      * @see android.os.Handler
238      * @see #set
239      * @see #setExact
240      * @see #setWindow
241      * @see #cancel
242      * @see android.content.Context#sendBroadcast
243      * @see android.content.Context#registerReceiver
244      * @see android.content.Intent#filterEquals
245      * @see #ELAPSED_REALTIME
246      * @see #ELAPSED_REALTIME_WAKEUP
247      * @see #RTC
248      * @see #RTC_WAKEUP
249      */
setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)250     public void setRepeating(int type, long triggerAtMillis,
251             long intervalMillis, PendingIntent operation) {
252         setImpl(type, triggerAtMillis, legacyExactLength(), intervalMillis, operation, null);
253     }
254 
255     /**
256      * Schedule an alarm to be delivered within a given window of time.  This method
257      * is similar to {@link #set(int, long, PendingIntent)}, but allows the
258      * application to precisely control the degree to which its delivery might be
259      * adjusted by the OS. This method allows an application to take advantage of the
260      * battery optimizations that arise from delivery batching even when it has
261      * modest timeliness requirements for its alarms.
262      *
263      * <p>
264      * This method can also be used to achieve strict ordering guarantees among
265      * multiple alarms by ensuring that the windows requested for each alarm do
266      * not intersect.
267      *
268      * <p>
269      * When precise delivery is not required, applications should use the standard
270      * {@link #set(int, long, PendingIntent)} method.  This will give the OS the most
271      * flexibility to minimize wakeups and battery use.  For alarms that must be delivered
272      * at precisely-specified times with no acceptable variation, applications can use
273      * {@link #setExact(int, long, PendingIntent)}.
274      *
275      * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
276      *        {@link #RTC}, or {@link #RTC_WAKEUP}.
277      * @param windowStartMillis The earliest time, in milliseconds, that the alarm should
278      *        be delivered, expressed in the appropriate clock's units (depending on the alarm
279      *        type).
280      * @param windowLengthMillis The length of the requested delivery window,
281      *        in milliseconds.  The alarm will be delivered no later than this many
282      *        milliseconds after {@code windowStartMillis}.  Note that this parameter
283      *        is a <i>duration,</i> not the timestamp of the end of the window.
284      * @param operation Action to perform when the alarm goes off;
285      *        typically comes from {@link PendingIntent#getBroadcast
286      *        IntentSender.getBroadcast()}.
287      *
288      * @see #set
289      * @see #setExact
290      * @see #setRepeating
291      * @see #cancel
292      * @see android.content.Context#sendBroadcast
293      * @see android.content.Context#registerReceiver
294      * @see android.content.Intent#filterEquals
295      * @see #ELAPSED_REALTIME
296      * @see #ELAPSED_REALTIME_WAKEUP
297      * @see #RTC
298      * @see #RTC_WAKEUP
299      */
setWindow(int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation)300     public void setWindow(int type, long windowStartMillis, long windowLengthMillis,
301             PendingIntent operation) {
302         setImpl(type, windowStartMillis, windowLengthMillis, 0, operation, null);
303     }
304 
305     /**
306      * Schedule an alarm to be delivered precisely at the stated time.
307      *
308      * <p>
309      * This method is like {@link #set(int, long, PendingIntent)}, but does not permit
310      * the OS to adjust the delivery time.  The alarm will be delivered as nearly as
311      * possible to the requested trigger time.
312      *
313      * <p>
314      * <b>Note:</b> only alarms for which there is a strong demand for exact-time
315      * delivery (such as an alarm clock ringing at the requested time) should be
316      * scheduled as exact.  Applications are strongly discouraged from using exact
317      * alarms unnecessarily as they reduce the OS's ability to minimize battery use.
318      *
319      * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
320      *        {@link #RTC}, or {@link #RTC_WAKEUP}.
321      * @param triggerAtMillis time in milliseconds that the alarm should go
322      *        off, using the appropriate clock (depending on the alarm type).
323      * @param operation Action to perform when the alarm goes off;
324      *        typically comes from {@link PendingIntent#getBroadcast
325      *        IntentSender.getBroadcast()}.
326      *
327      * @see #set
328      * @see #setRepeating
329      * @see #setWindow
330      * @see #cancel
331      * @see android.content.Context#sendBroadcast
332      * @see android.content.Context#registerReceiver
333      * @see android.content.Intent#filterEquals
334      * @see #ELAPSED_REALTIME
335      * @see #ELAPSED_REALTIME_WAKEUP
336      * @see #RTC
337      * @see #RTC_WAKEUP
338      */
setExact(int type, long triggerAtMillis, PendingIntent operation)339     public void setExact(int type, long triggerAtMillis, PendingIntent operation) {
340         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, operation, null);
341     }
342 
343     /** @hide */
set(int type, long triggerAtMillis, long windowMillis, long intervalMillis, PendingIntent operation, WorkSource workSource)344     public void set(int type, long triggerAtMillis, long windowMillis, long intervalMillis,
345             PendingIntent operation, WorkSource workSource) {
346         setImpl(type, triggerAtMillis, windowMillis, intervalMillis, operation, workSource);
347     }
348 
setImpl(int type, long triggerAtMillis, long windowMillis, long intervalMillis, PendingIntent operation, WorkSource workSource)349     private void setImpl(int type, long triggerAtMillis, long windowMillis, long intervalMillis,
350             PendingIntent operation, WorkSource workSource) {
351         if (triggerAtMillis < 0) {
352             /* NOTYET
353             if (mAlwaysExact) {
354                 // Fatal error for KLP+ apps to use negative trigger times
355                 throw new IllegalArgumentException("Invalid alarm trigger time "
356                         + triggerAtMillis);
357             }
358             */
359             triggerAtMillis = 0;
360         }
361 
362         try {
363             mService.set(type, triggerAtMillis, windowMillis, intervalMillis, operation,
364                     workSource);
365         } catch (RemoteException ex) {
366         }
367     }
368 
369     /**
370      * Available inexact recurrence interval recognized by
371      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
372      * when running on Android prior to API 19.
373      */
374     public static final long INTERVAL_FIFTEEN_MINUTES = 15 * 60 * 1000;
375 
376     /**
377      * Available inexact recurrence interval recognized by
378      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
379      * when running on Android prior to API 19.
380      */
381     public static final long INTERVAL_HALF_HOUR = 2*INTERVAL_FIFTEEN_MINUTES;
382 
383     /**
384      * Available inexact recurrence interval recognized by
385      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
386      * when running on Android prior to API 19.
387      */
388     public static final long INTERVAL_HOUR = 2*INTERVAL_HALF_HOUR;
389 
390     /**
391      * Available inexact recurrence interval recognized by
392      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
393      * when running on Android prior to API 19.
394      */
395     public static final long INTERVAL_HALF_DAY = 12*INTERVAL_HOUR;
396 
397     /**
398      * Available inexact recurrence interval recognized by
399      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
400      * when running on Android prior to API 19.
401      */
402     public static final long INTERVAL_DAY = 2*INTERVAL_HALF_DAY;
403 
404     /**
405      * Schedule a repeating alarm that has inexact trigger time requirements;
406      * for example, an alarm that repeats every hour, but not necessarily at
407      * the top of every hour.  These alarms are more power-efficient than
408      * the strict recurrences traditionally supplied by {@link #setRepeating}, since the
409      * system can adjust alarms' delivery times to cause them to fire simultaneously,
410      * avoiding waking the device from sleep more than necessary.
411      *
412      * <p>Your alarm's first trigger will not be before the requested time,
413      * but it might not occur for almost a full interval after that time.  In
414      * addition, while the overall period of the repeating alarm will be as
415      * requested, the time between any two successive firings of the alarm
416      * may vary.  If your application demands very low jitter, use
417      * one-shot alarms with an appropriate window instead; see {@link
418      * #setWindow(int, long, long, PendingIntent)} and
419      * {@link #setExact(int, long, PendingIntent)}.
420      *
421      * <p class="note">
422      * As of API 19, all repeating alarms are inexact.  Because this method has
423      * been available since API 3, your application can safely call it and be
424      * assured that it will get similar behavior on both current and older versions
425      * of Android.
426      *
427      * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
428      *        {@link #RTC}, or {@link #RTC_WAKEUP}.
429      * @param triggerAtMillis time in milliseconds that the alarm should first
430      * go off, using the appropriate clock (depending on the alarm type).  This
431      * is inexact: the alarm will not fire before this time, but there may be a
432      * delay of almost an entire alarm interval before the first invocation of
433      * the alarm.
434      * @param intervalMillis interval in milliseconds between subsequent repeats
435      * of the alarm.  Prior to API 19, if this is one of INTERVAL_FIFTEEN_MINUTES,
436      * INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY
437      * then the alarm will be phase-aligned with other alarms to reduce the
438      * number of wakeups.  Otherwise, the alarm will be set as though the
439      * application had called {@link #setRepeating}.  As of API 19, all repeating
440      * alarms will be inexact and subject to batching with other alarms regardless
441      * of their stated repeat interval.
442      * @param operation Action to perform when the alarm goes off;
443      * typically comes from {@link PendingIntent#getBroadcast
444      * IntentSender.getBroadcast()}.
445      *
446      * @see android.os.Handler
447      * @see #set
448      * @see #cancel
449      * @see android.content.Context#sendBroadcast
450      * @see android.content.Context#registerReceiver
451      * @see android.content.Intent#filterEquals
452      * @see #ELAPSED_REALTIME
453      * @see #ELAPSED_REALTIME_WAKEUP
454      * @see #RTC
455      * @see #RTC_WAKEUP
456      * @see #INTERVAL_FIFTEEN_MINUTES
457      * @see #INTERVAL_HALF_HOUR
458      * @see #INTERVAL_HOUR
459      * @see #INTERVAL_HALF_DAY
460      * @see #INTERVAL_DAY
461      */
setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)462     public void setInexactRepeating(int type, long triggerAtMillis,
463             long intervalMillis, PendingIntent operation) {
464         setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, intervalMillis, operation, null);
465     }
466 
467     /**
468      * Remove any alarms with a matching {@link Intent}.
469      * Any alarm, of any type, whose Intent matches this one (as defined by
470      * {@link Intent#filterEquals}), will be canceled.
471      *
472      * @param operation IntentSender which matches a previously added
473      * IntentSender.
474      *
475      * @see #set
476      */
cancel(PendingIntent operation)477     public void cancel(PendingIntent operation) {
478         try {
479             mService.remove(operation);
480         } catch (RemoteException ex) {
481         }
482     }
483 
484     /**
485      * Set the system wall clock time.
486      * Requires the permission android.permission.SET_TIME.
487      *
488      * @param millis time in milliseconds since the Epoch
489      */
setTime(long millis)490     public void setTime(long millis) {
491         try {
492             mService.setTime(millis);
493         } catch (RemoteException ex) {
494         }
495     }
496 
497     /**
498      * Set the system default time zone.
499      * Requires the permission android.permission.SET_TIME_ZONE.
500      *
501      * @param timeZone in the format understood by {@link java.util.TimeZone}
502      */
setTimeZone(String timeZone)503     public void setTimeZone(String timeZone) {
504         try {
505             mService.setTimeZone(timeZone);
506         } catch (RemoteException ex) {
507         }
508     }
509 }
510