AlarmManager.java revision 3d1933c45fe9ba2389ebd166d96abeceab1971d1
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
17package android.app;
18
19import android.annotation.SdkConstant;
20import android.annotation.SystemApi;
21import android.content.Context;
22import android.content.Intent;
23import android.os.Build;
24import android.os.Parcel;
25import android.os.Parcelable;
26import android.os.RemoteException;
27import android.os.UserHandle;
28import android.os.WorkSource;
29import android.text.TextUtils;
30import libcore.util.ZoneInfoDB;
31
32import java.io.IOException;
33
34/**
35 * This class provides access to the system alarm services.  These allow you
36 * to schedule your application to be run at some point in the future.  When
37 * an alarm goes off, the {@link Intent} that had been registered for it
38 * is broadcast by the system, automatically starting the target application
39 * if it is not already running.  Registered alarms are retained while the
40 * device is asleep (and can optionally wake the device up if they go off
41 * during that time), but will be cleared if it is turned off and rebooted.
42 *
43 * <p>The Alarm Manager holds a CPU wake lock as long as the alarm receiver's
44 * onReceive() method is executing. This guarantees that the phone will not sleep
45 * until you have finished handling the broadcast. Once onReceive() returns, the
46 * Alarm Manager releases this wake lock. This means that the phone will in some
47 * cases sleep as soon as your onReceive() method completes.  If your alarm receiver
48 * called {@link android.content.Context#startService Context.startService()}, it
49 * is possible that the phone will sleep before the requested service is launched.
50 * To prevent this, your BroadcastReceiver and Service will need to implement a
51 * separate wake lock policy to ensure that the phone continues running until the
52 * service becomes available.
53 *
54 * <p><b>Note: The Alarm Manager is intended for cases where you want to have
55 * your application code run at a specific time, even if your application is
56 * not currently running.  For normal timing operations (ticks, timeouts,
57 * etc) it is easier and much more efficient to use
58 * {@link android.os.Handler}.</b>
59 *
60 * <p class="caution"><strong>Note:</strong> Beginning with API 19
61 * ({@link android.os.Build.VERSION_CODES#KITKAT}) alarm delivery is inexact:
62 * the OS will shift alarms in order to minimize wakeups and battery use.  There are
63 * new APIs to support applications which need strict delivery guarantees; see
64 * {@link #setWindow(int, long, long, PendingIntent)} and
65 * {@link #setExact(int, long, PendingIntent)}.  Applications whose {@code targetSdkVersion}
66 * is earlier than API 19 will continue to see the previous behavior in which all
67 * alarms are delivered exactly when requested.
68 *
69 * <p>You do not
70 * instantiate this class directly; instead, retrieve it through
71 * {@link android.content.Context#getSystemService
72 * Context.getSystemService(Context.ALARM_SERVICE)}.
73 */
74public class AlarmManager {
75    /**
76     * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
77     * (wall clock time in UTC), which will wake up the device when
78     * it goes off.
79     */
80    public static final int RTC_WAKEUP = 0;
81    /**
82     * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
83     * (wall clock time in UTC).  This alarm does not wake the
84     * device up; if it goes off while the device is asleep, it will not be
85     * delivered until the next time the device wakes up.
86     */
87    public static final int RTC = 1;
88    /**
89     * Alarm time in {@link android.os.SystemClock#elapsedRealtime
90     * SystemClock.elapsedRealtime()} (time since boot, including sleep),
91     * which will wake up the device when it goes off.
92     */
93    public static final int ELAPSED_REALTIME_WAKEUP = 2;
94    /**
95     * Alarm time in {@link android.os.SystemClock#elapsedRealtime
96     * SystemClock.elapsedRealtime()} (time since boot, including sleep).
97     * This alarm does not wake the device up; if it goes off while the device
98     * is asleep, it will not be delivered until the next time the device
99     * wakes up.
100     */
101    public static final int ELAPSED_REALTIME = 3;
102
103    /**
104     * Broadcast Action: Sent after the value returned by
105     * {@link #getNextAlarmClock()} has changed.
106     *
107     * <p class="note">This is a protected intent that can only be sent by the system.
108     * It is only sent to registered receivers.</p>
109     */
110    @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
111    public static final String ACTION_NEXT_ALARM_CLOCK_CHANGED =
112            "android.app.action.NEXT_ALARM_CLOCK_CHANGED";
113
114    /** @hide */
115    public static final long WINDOW_EXACT = 0;
116    /** @hide */
117    public static final long WINDOW_HEURISTIC = -1;
118
119    /**
120     * Flag for alarms: this is to be a stand-alone alarm, that should not be batched with
121     * other alarms.
122     * @hide
123     */
124    public static final int FLAG_STANDALONE = 1<<0;
125
126    /**
127     * Flag for alarms: this alarm would like to wake the device even if it is idle.  This
128     * is, for example, an alarm for an alarm clock.
129     * @hide
130     */
131    public static final int FLAG_WAKE_FROM_IDLE = 1<<1;
132
133    /**
134     * Flag for alarms: this alarm would like to still execute even if the device is
135     * idle.  This won't bring the device out of idle, just allow this specific alarm to
136     * run.  Note that this means the actual time this alarm goes off can be inconsistent
137     * with the time of non-allow-while-idle alarms (it could go earlier than the time
138     * requested by another alarm).
139     *
140     * @hide
141     */
142    public static final int FLAG_ALLOW_WHILE_IDLE = 1<<2;
143
144    /**
145     * Flag for alarms: same as {@link #FLAG_ALLOW_WHILE_IDLE}, but doesn't have restrictions
146     * on how frequently it can be scheduled.  Only available (and automatically applied) to
147     * system alarms.
148     *
149     * @hide
150     */
151    public static final int FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED = 1<<3;
152
153    /**
154     * Flag for alarms: this alarm marks the point where we would like to come out of idle
155     * mode.  It may be moved by the alarm manager to match the first wake-from-idle alarm.
156     * Scheduling an alarm with this flag puts the alarm manager in to idle mode, where it
157     * avoids scheduling any further alarms until the marker alarm is executed.
158     * @hide
159     */
160    public static final int FLAG_IDLE_UNTIL = 1<<4;
161
162    private final IAlarmManager mService;
163    private final boolean mAlwaysExact;
164    private final int mTargetSdkVersion;
165
166
167    /**
168     * package private on purpose
169     */
170    AlarmManager(IAlarmManager service, Context ctx) {
171        mService = service;
172
173        mTargetSdkVersion = ctx.getApplicationInfo().targetSdkVersion;
174        mAlwaysExact = (mTargetSdkVersion < Build.VERSION_CODES.KITKAT);
175    }
176
177    private long legacyExactLength() {
178        return (mAlwaysExact ? WINDOW_EXACT : WINDOW_HEURISTIC);
179    }
180
181    /**
182     * <p>Schedule an alarm.  <b>Note: for timing operations (ticks, timeouts,
183     * etc) it is easier and much more efficient to use {@link android.os.Handler}.</b>
184     * If there is already an alarm scheduled for the same IntentSender, that previous
185     * alarm will first be canceled.
186     *
187     * <p>If the stated trigger time is in the past, the alarm will be triggered
188     * immediately.  If there is already an alarm for this Intent
189     * scheduled (with the equality of two intents being defined by
190     * {@link Intent#filterEquals}), then it will be removed and replaced by
191     * this one.
192     *
193     * <p>
194     * The alarm is an Intent broadcast that goes to a broadcast receiver that
195     * you registered with {@link android.content.Context#registerReceiver}
196     * or through the &lt;receiver&gt; tag in an AndroidManifest.xml file.
197     *
198     * <p>
199     * Alarm intents are delivered with a data extra of type int called
200     * {@link Intent#EXTRA_ALARM_COUNT Intent.EXTRA_ALARM_COUNT} that indicates
201     * how many past alarm events have been accumulated into this intent
202     * broadcast.  Recurring alarms that have gone undelivered because the
203     * phone was asleep may have a count greater than one when delivered.
204     *
205     * <div class="note">
206     * <p>
207     * <b>Note:</b> Beginning in API 19, the trigger time passed to this method
208     * is treated as inexact: the alarm will not be delivered before this time, but
209     * may be deferred and delivered some time later.  The OS will use
210     * this policy in order to "batch" alarms together across the entire system,
211     * minimizing the number of times the device needs to "wake up" and minimizing
212     * battery use.  In general, alarms scheduled in the near future will not
213     * be deferred as long as alarms scheduled far in the future.
214     *
215     * <p>
216     * With the new batching policy, delivery ordering guarantees are not as
217     * strong as they were previously.  If the application sets multiple alarms,
218     * it is possible that these alarms' <em>actual</em> delivery ordering may not match
219     * the order of their <em>requested</em> delivery times.  If your application has
220     * strong ordering requirements there are other APIs that you can use to get
221     * the necessary behavior; see {@link #setWindow(int, long, long, PendingIntent)}
222     * and {@link #setExact(int, long, PendingIntent)}.
223     *
224     * <p>
225     * Applications whose {@code targetSdkVersion} is before API 19 will
226     * continue to get the previous alarm behavior: all of their scheduled alarms
227     * will be treated as exact.
228     * </div>
229     *
230     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
231     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
232     * @param triggerAtMillis time in milliseconds that the alarm should go
233     * off, using the appropriate clock (depending on the alarm type).
234     * @param operation Action to perform when the alarm goes off;
235     * typically comes from {@link PendingIntent#getBroadcast
236     * IntentSender.getBroadcast()}.
237     *
238     * @see android.os.Handler
239     * @see #setExact
240     * @see #setRepeating
241     * @see #setWindow
242     * @see #cancel
243     * @see android.content.Context#sendBroadcast
244     * @see android.content.Context#registerReceiver
245     * @see android.content.Intent#filterEquals
246     * @see #ELAPSED_REALTIME
247     * @see #ELAPSED_REALTIME_WAKEUP
248     * @see #RTC
249     * @see #RTC_WAKEUP
250     */
251    public void set(int type, long triggerAtMillis, PendingIntent operation) {
252        setImpl(type, triggerAtMillis, legacyExactLength(), 0, 0, operation, null, null);
253    }
254
255    /**
256     * Schedule a repeating alarm.  <b>Note: for timing operations (ticks,
257     * timeouts, etc) it is easier and much more efficient to use
258     * {@link android.os.Handler}.</b>  If there is already an alarm scheduled
259     * for the same IntentSender, it will first be canceled.
260     *
261     * <p>Like {@link #set}, except you can also supply a period at which
262     * the alarm will automatically repeat.  This alarm continues
263     * repeating until explicitly removed with {@link #cancel}.  If the stated
264     * trigger time is in the past, the alarm will be triggered immediately, with an
265     * alarm count depending on how far in the past the trigger time is relative
266     * to the repeat interval.
267     *
268     * <p>If an alarm is delayed (by system sleep, for example, for non
269     * _WAKEUP alarm types), a skipped repeat will be delivered as soon as
270     * possible.  After that, future alarms will be delivered according to the
271     * original schedule; they do not drift over time.  For example, if you have
272     * set a recurring alarm for the top of every hour but the phone was asleep
273     * from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens,
274     * then the next alarm will be sent at 9:00.
275     *
276     * <p>If your application wants to allow the delivery times to drift in
277     * order to guarantee that at least a certain time interval always elapses
278     * between alarms, then the approach to take is to use one-time alarms,
279     * scheduling the next one yourself when handling each alarm delivery.
280     *
281     * <p class="note">
282     * <b>Note:</b> as of API 19, all repeating alarms are inexact.  If your
283     * application needs precise delivery times then it must use one-time
284     * exact alarms, rescheduling each time as described above. Legacy applications
285     * whose {@code targetSdkVersion} is earlier than API 19 will continue to have all
286     * of their alarms, including repeating alarms, treated as exact.
287     *
288     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
289     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
290     * @param triggerAtMillis time in milliseconds that the alarm should first
291     * go off, using the appropriate clock (depending on the alarm type).
292     * @param intervalMillis interval in milliseconds between subsequent repeats
293     * of the alarm.
294     * @param operation Action to perform when the alarm goes off;
295     * typically comes from {@link PendingIntent#getBroadcast
296     * IntentSender.getBroadcast()}.
297     *
298     * @see android.os.Handler
299     * @see #set
300     * @see #setExact
301     * @see #setWindow
302     * @see #cancel
303     * @see android.content.Context#sendBroadcast
304     * @see android.content.Context#registerReceiver
305     * @see android.content.Intent#filterEquals
306     * @see #ELAPSED_REALTIME
307     * @see #ELAPSED_REALTIME_WAKEUP
308     * @see #RTC
309     * @see #RTC_WAKEUP
310     */
311    public void setRepeating(int type, long triggerAtMillis,
312            long intervalMillis, PendingIntent operation) {
313        setImpl(type, triggerAtMillis, legacyExactLength(), intervalMillis, 0, operation, null,
314                null);
315    }
316
317    /**
318     * Schedule an alarm to be delivered within a given window of time.  This method
319     * is similar to {@link #set(int, long, PendingIntent)}, but allows the
320     * application to precisely control the degree to which its delivery might be
321     * adjusted by the OS. This method allows an application to take advantage of the
322     * battery optimizations that arise from delivery batching even when it has
323     * modest timeliness requirements for its alarms.
324     *
325     * <p>
326     * This method can also be used to achieve strict ordering guarantees among
327     * multiple alarms by ensuring that the windows requested for each alarm do
328     * not intersect.
329     *
330     * <p>
331     * When precise delivery is not required, applications should use the standard
332     * {@link #set(int, long, PendingIntent)} method.  This will give the OS the most
333     * flexibility to minimize wakeups and battery use.  For alarms that must be delivered
334     * at precisely-specified times with no acceptable variation, applications can use
335     * {@link #setExact(int, long, PendingIntent)}.
336     *
337     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
338     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
339     * @param windowStartMillis The earliest time, in milliseconds, that the alarm should
340     *        be delivered, expressed in the appropriate clock's units (depending on the alarm
341     *        type).
342     * @param windowLengthMillis The length of the requested delivery window,
343     *        in milliseconds.  The alarm will be delivered no later than this many
344     *        milliseconds after {@code windowStartMillis}.  Note that this parameter
345     *        is a <i>duration,</i> not the timestamp of the end of the window.
346     * @param operation Action to perform when the alarm goes off;
347     *        typically comes from {@link PendingIntent#getBroadcast
348     *        IntentSender.getBroadcast()}.
349     *
350     * @see #set
351     * @see #setExact
352     * @see #setRepeating
353     * @see #cancel
354     * @see android.content.Context#sendBroadcast
355     * @see android.content.Context#registerReceiver
356     * @see android.content.Intent#filterEquals
357     * @see #ELAPSED_REALTIME
358     * @see #ELAPSED_REALTIME_WAKEUP
359     * @see #RTC
360     * @see #RTC_WAKEUP
361     */
362    public void setWindow(int type, long windowStartMillis, long windowLengthMillis,
363            PendingIntent operation) {
364        setImpl(type, windowStartMillis, windowLengthMillis, 0, 0, operation, null, null);
365    }
366
367    /**
368     * Schedule an alarm to be delivered precisely at the stated time.
369     *
370     * <p>
371     * This method is like {@link #set(int, long, PendingIntent)}, but does not permit
372     * the OS to adjust the delivery time.  The alarm will be delivered as nearly as
373     * possible to the requested trigger time.
374     *
375     * <p>
376     * <b>Note:</b> only alarms for which there is a strong demand for exact-time
377     * delivery (such as an alarm clock ringing at the requested time) should be
378     * scheduled as exact.  Applications are strongly discouraged from using exact
379     * alarms unnecessarily as they reduce the OS's ability to minimize battery use.
380     *
381     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
382     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
383     * @param triggerAtMillis time in milliseconds that the alarm should go
384     *        off, using the appropriate clock (depending on the alarm type).
385     * @param operation Action to perform when the alarm goes off;
386     *        typically comes from {@link PendingIntent#getBroadcast
387     *        IntentSender.getBroadcast()}.
388     *
389     * @see #set
390     * @see #setRepeating
391     * @see #setWindow
392     * @see #cancel
393     * @see android.content.Context#sendBroadcast
394     * @see android.content.Context#registerReceiver
395     * @see android.content.Intent#filterEquals
396     * @see #ELAPSED_REALTIME
397     * @see #ELAPSED_REALTIME_WAKEUP
398     * @see #RTC
399     * @see #RTC_WAKEUP
400     */
401    public void setExact(int type, long triggerAtMillis, PendingIntent operation) {
402        setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, operation, null, null);
403    }
404
405    /**
406     * Schedule an idle-until alarm, which will keep the alarm manager idle until
407     * the given time.
408     * @hide
409     */
410    public void setIdleUntil(int type, long triggerAtMillis, PendingIntent operation) {
411        setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_IDLE_UNTIL, operation, null, null);
412    }
413
414    /**
415     * Schedule an alarm that represents an alarm clock.
416     *
417     * The system may choose to display information about this alarm to the user.
418     *
419     * <p>
420     * This method is like {@link #setExact(int, long, PendingIntent)}, but implies
421     * {@link #RTC_WAKEUP}.
422     *
423     * @param info
424     * @param operation Action to perform when the alarm goes off;
425     *        typically comes from {@link PendingIntent#getBroadcast
426     *        IntentSender.getBroadcast()}.
427     *
428     * @see #set
429     * @see #setRepeating
430     * @see #setWindow
431     * @see #setExact
432     * @see #cancel
433     * @see #getNextAlarmClock()
434     * @see android.content.Context#sendBroadcast
435     * @see android.content.Context#registerReceiver
436     * @see android.content.Intent#filterEquals
437     */
438    public void setAlarmClock(AlarmClockInfo info, PendingIntent operation) {
439        setImpl(RTC_WAKEUP, info.getTriggerTime(), WINDOW_EXACT, 0, 0, operation, null, info);
440    }
441
442    /** @hide */
443    @SystemApi
444    public void set(int type, long triggerAtMillis, long windowMillis, long intervalMillis,
445            PendingIntent operation, WorkSource workSource) {
446        setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, operation, workSource,
447                null);
448    }
449
450    private void setImpl(int type, long triggerAtMillis, long windowMillis, long intervalMillis,
451            int flags, PendingIntent operation, WorkSource workSource, AlarmClockInfo alarmClock) {
452        if (triggerAtMillis < 0) {
453            /* NOTYET
454            if (mAlwaysExact) {
455                // Fatal error for KLP+ apps to use negative trigger times
456                throw new IllegalArgumentException("Invalid alarm trigger time "
457                        + triggerAtMillis);
458            }
459            */
460            triggerAtMillis = 0;
461        }
462
463        try {
464            mService.set(type, triggerAtMillis, windowMillis, intervalMillis, flags, operation,
465                    workSource, alarmClock);
466        } catch (RemoteException ex) {
467        }
468    }
469
470    /**
471     * Available inexact recurrence interval recognized by
472     * {@link #setInexactRepeating(int, long, long, PendingIntent)}
473     * when running on Android prior to API 19.
474     */
475    public static final long INTERVAL_FIFTEEN_MINUTES = 15 * 60 * 1000;
476
477    /**
478     * Available inexact recurrence interval recognized by
479     * {@link #setInexactRepeating(int, long, long, PendingIntent)}
480     * when running on Android prior to API 19.
481     */
482    public static final long INTERVAL_HALF_HOUR = 2*INTERVAL_FIFTEEN_MINUTES;
483
484    /**
485     * Available inexact recurrence interval recognized by
486     * {@link #setInexactRepeating(int, long, long, PendingIntent)}
487     * when running on Android prior to API 19.
488     */
489    public static final long INTERVAL_HOUR = 2*INTERVAL_HALF_HOUR;
490
491    /**
492     * Available inexact recurrence interval recognized by
493     * {@link #setInexactRepeating(int, long, long, PendingIntent)}
494     * when running on Android prior to API 19.
495     */
496    public static final long INTERVAL_HALF_DAY = 12*INTERVAL_HOUR;
497
498    /**
499     * Available inexact recurrence interval recognized by
500     * {@link #setInexactRepeating(int, long, long, PendingIntent)}
501     * when running on Android prior to API 19.
502     */
503    public static final long INTERVAL_DAY = 2*INTERVAL_HALF_DAY;
504
505    /**
506     * Schedule a repeating alarm that has inexact trigger time requirements;
507     * for example, an alarm that repeats every hour, but not necessarily at
508     * the top of every hour.  These alarms are more power-efficient than
509     * the strict recurrences traditionally supplied by {@link #setRepeating}, since the
510     * system can adjust alarms' delivery times to cause them to fire simultaneously,
511     * avoiding waking the device from sleep more than necessary.
512     *
513     * <p>Your alarm's first trigger will not be before the requested time,
514     * but it might not occur for almost a full interval after that time.  In
515     * addition, while the overall period of the repeating alarm will be as
516     * requested, the time between any two successive firings of the alarm
517     * may vary.  If your application demands very low jitter, use
518     * one-shot alarms with an appropriate window instead; see {@link
519     * #setWindow(int, long, long, PendingIntent)} and
520     * {@link #setExact(int, long, PendingIntent)}.
521     *
522     * <p class="note">
523     * As of API 19, all repeating alarms are inexact.  Because this method has
524     * been available since API 3, your application can safely call it and be
525     * assured that it will get similar behavior on both current and older versions
526     * of Android.
527     *
528     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
529     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
530     * @param triggerAtMillis time in milliseconds that the alarm should first
531     * go off, using the appropriate clock (depending on the alarm type).  This
532     * is inexact: the alarm will not fire before this time, but there may be a
533     * delay of almost an entire alarm interval before the first invocation of
534     * the alarm.
535     * @param intervalMillis interval in milliseconds between subsequent repeats
536     * of the alarm.  Prior to API 19, if this is one of INTERVAL_FIFTEEN_MINUTES,
537     * INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY
538     * then the alarm will be phase-aligned with other alarms to reduce the
539     * number of wakeups.  Otherwise, the alarm will be set as though the
540     * application had called {@link #setRepeating}.  As of API 19, all repeating
541     * alarms will be inexact and subject to batching with other alarms regardless
542     * of their stated repeat interval.
543     * @param operation Action to perform when the alarm goes off;
544     * typically comes from {@link PendingIntent#getBroadcast
545     * IntentSender.getBroadcast()}.
546     *
547     * @see android.os.Handler
548     * @see #set
549     * @see #cancel
550     * @see android.content.Context#sendBroadcast
551     * @see android.content.Context#registerReceiver
552     * @see android.content.Intent#filterEquals
553     * @see #ELAPSED_REALTIME
554     * @see #ELAPSED_REALTIME_WAKEUP
555     * @see #RTC
556     * @see #RTC_WAKEUP
557     * @see #INTERVAL_FIFTEEN_MINUTES
558     * @see #INTERVAL_HALF_HOUR
559     * @see #INTERVAL_HOUR
560     * @see #INTERVAL_HALF_DAY
561     * @see #INTERVAL_DAY
562     */
563    public void setInexactRepeating(int type, long triggerAtMillis,
564            long intervalMillis, PendingIntent operation) {
565        setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, intervalMillis, 0, operation, null, null);
566    }
567
568    /**
569     * Like {@link #set(int, long, PendingIntent)}, but this alarm will be allowed to execute
570     * even when the system is in low-power idle modes.  This type of alarm must <b>only</b>
571     * be used for situations where it is actually required that the alarm go off while in
572     * idle -- a reasonable example would be for a calendar notification that should make a
573     * sound so the user is aware of it.  These alarms can significantly impact the power use
574     * of the device when idle (and thus cause significant battery blame to the app scheduling
575     * them), so they should be used with care.
576     *
577     * <p>To reduce abuse, there are restrictions on how frequently these alarms will go off
578     * for a particular application.  Under normal system operation, it will not dispatch these
579     * alarms more than about every minute (at which point every such pending alarm is
580     * dispatched); when in low-power idle modes this duration may be significantly longer,
581     * such as 15 minutes.</p>
582     *
583     * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
584     * out of order with any other alarms, even those from the same app.  This will clearly happen
585     * when the device is idle (since this alarm can go off while idle, when any other alarms
586     * from the app will be held until later), but may also happen even when not idle.</p>
587     *
588     * <p>Regardless of the app's target SDK version, this call always allows batching of the
589     * alarm.</p>
590     *
591     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
592     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
593     * @param triggerAtMillis time in milliseconds that the alarm should go
594     * off, using the appropriate clock (depending on the alarm type).
595     * @param operation Action to perform when the alarm goes off;
596     * typically comes from {@link PendingIntent#getBroadcast
597     * IntentSender.getBroadcast()}.
598     *
599     * @see #set(int, long, PendingIntent)
600     * @see #setExactAndAllowWhileIdle
601     * @see #cancel
602     * @see android.content.Context#sendBroadcast
603     * @see android.content.Context#registerReceiver
604     * @see android.content.Intent#filterEquals
605     * @see #ELAPSED_REALTIME
606     * @see #ELAPSED_REALTIME_WAKEUP
607     * @see #RTC
608     * @see #RTC_WAKEUP
609     */
610    public void setAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation) {
611        setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, 0, FLAG_ALLOW_WHILE_IDLE, operation,
612                null, null);
613    }
614
615    /**
616     * Like {@link #setExact(int, long, PendingIntent)}, but this alarm will be allowed to execute
617     * even when the system is in low-power idle modes.  If you don't need exact scheduling of
618     * the alarm but still need to execute while idle, consider using
619     * {@link #setAndAllowWhileIdle}.  This type of alarm must <b>only</b>
620     * be used for situations where it is actually required that the alarm go off while in
621     * idle -- a reasonable example would be for a calendar notification that should make a
622     * sound so the user is aware of it.  These alarms can significantly impact the power use
623     * of the device when idle (and thus cause significant battery blame to the app scheduling
624     * them), so they should be used with care.
625     *
626     * <p>To reduce abuse, there are restrictions on how frequently these alarms will go off
627     * for a particular application.  Under normal system operation, it will not dispatch these
628     * alarms more than about every minute (at which point every such pending alarm is
629     * dispatched); when in low-power idle modes this duration may be significantly longer,
630     * such as 15 minutes.</p>
631     *
632     * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
633     * out of order with any other alarms, even those from the same app.  This will clearly happen
634     * when the device is idle (since this alarm can go off while idle, when any other alarms
635     * from the app will be held until later), but may also happen even when not idle.
636     * Note that the OS will allow itself more flexibility for scheduling these alarms than
637     * regular exact alarms, since the application has opted into this behavior.  When the
638     * device is idle it may take even more liberties with scheduling in order to optimize
639     * for battery life.</p>
640     *
641     * @param type One of {@link #ELAPSED_REALTIME}, {@link #ELAPSED_REALTIME_WAKEUP},
642     *        {@link #RTC}, or {@link #RTC_WAKEUP}.
643     * @param triggerAtMillis time in milliseconds that the alarm should go
644     *        off, using the appropriate clock (depending on the alarm type).
645     * @param operation Action to perform when the alarm goes off;
646     *        typically comes from {@link PendingIntent#getBroadcast
647     *        IntentSender.getBroadcast()}.
648     *
649     * @see #set
650     * @see #setRepeating
651     * @see #setWindow
652     * @see #cancel
653     * @see android.content.Context#sendBroadcast
654     * @see android.content.Context#registerReceiver
655     * @see android.content.Intent#filterEquals
656     * @see #ELAPSED_REALTIME
657     * @see #ELAPSED_REALTIME_WAKEUP
658     * @see #RTC
659     * @see #RTC_WAKEUP
660     */
661    public void setExactAndAllowWhileIdle(int type, long triggerAtMillis, PendingIntent operation) {
662        setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_ALLOW_WHILE_IDLE, operation,
663                null, null);
664    }
665
666    /**
667     * Remove any alarms with a matching {@link Intent}.
668     * Any alarm, of any type, whose Intent matches this one (as defined by
669     * {@link Intent#filterEquals}), will be canceled.
670     *
671     * @param operation IntentSender which matches a previously added
672     * IntentSender.
673     *
674     * @see #set
675     */
676    public void cancel(PendingIntent operation) {
677        try {
678            mService.remove(operation);
679        } catch (RemoteException ex) {
680        }
681    }
682
683    /**
684     * Set the system wall clock time.
685     * Requires the permission android.permission.SET_TIME.
686     *
687     * @param millis time in milliseconds since the Epoch
688     */
689    public void setTime(long millis) {
690        try {
691            mService.setTime(millis);
692        } catch (RemoteException ex) {
693        }
694    }
695
696    /**
697     * Sets the system's persistent default time zone. This is the time zone for all apps, even
698     * after a reboot. Use {@link java.util.TimeZone#setDefault} if you just want to change the
699     * time zone within your app, and even then prefer to pass an explicit
700     * {@link java.util.TimeZone} to APIs that require it rather than changing the time zone for
701     * all threads.
702     *
703     * <p> On android M and above, it is an error to pass in a non-Olson timezone to this
704     * function. Note that this is a bad idea on all Android releases because POSIX and
705     * the {@code TimeZone} class have opposite interpretations of {@code '+'} and {@code '-'}
706     * in the same non-Olson ID.
707     *
708     * @param timeZone one of the Olson ids from the list returned by
709     *     {@link java.util.TimeZone#getAvailableIDs}
710     */
711    public void setTimeZone(String timeZone) {
712        if (TextUtils.isEmpty(timeZone)) {
713            return;
714        }
715
716        // Reject this timezone if it isn't an Olson zone we recognize.
717        if (mTargetSdkVersion >= Build.VERSION_CODES.MNC) {
718            boolean hasTimeZone = false;
719            try {
720                hasTimeZone = ZoneInfoDB.getInstance().hasTimeZone(timeZone);
721            } catch (IOException ignored) {
722            }
723
724            if (!hasTimeZone) {
725                throw new IllegalArgumentException("Timezone: " + timeZone + " is not an Olson ID");
726            }
727        }
728
729        try {
730            mService.setTimeZone(timeZone);
731        } catch (RemoteException ex) {
732        }
733    }
734
735    /** @hide */
736    public long getNextWakeFromIdleTime() {
737        try {
738            return mService.getNextWakeFromIdleTime();
739        } catch (RemoteException ex) {
740            return Long.MAX_VALUE;
741        }
742    }
743
744    /**
745     * Gets information about the next alarm clock currently scheduled.
746     *
747     * The alarm clocks considered are those scheduled by {@link #setAlarmClock}
748     * from any package of the calling user.
749     *
750     * @see #setAlarmClock
751     * @see AlarmClockInfo
752     */
753    public AlarmClockInfo getNextAlarmClock() {
754        return getNextAlarmClock(UserHandle.myUserId());
755    }
756
757    /**
758     * Gets information about the next alarm clock currently scheduled.
759     *
760     * The alarm clocks considered are those scheduled by {@link #setAlarmClock}
761     * from any package of the given {@parm userId}.
762     *
763     * @see #setAlarmClock
764     * @see AlarmClockInfo
765     *
766     * @hide
767     */
768    public AlarmClockInfo getNextAlarmClock(int userId) {
769        try {
770            return mService.getNextAlarmClock(userId);
771        } catch (RemoteException ex) {
772            return null;
773        }
774    }
775
776    /**
777     * An immutable description of an alarm clock.
778     *
779     * @see AlarmManager#setAlarmClock
780     * @see AlarmManager#getNextAlarmClock
781     */
782    public static final class AlarmClockInfo implements Parcelable {
783
784        private final long mTriggerTime;
785        private final PendingIntent mShowIntent;
786
787        /**
788         * Creates a new alarm clock description.
789         *
790         * @param triggerTime time at which the underlying alarm is triggered in wall time
791         *                    milliseconds since the epoch
792         * @param showIntent an intent that can be used to show or edit details of
793         *                        the alarm clock.
794         */
795        public AlarmClockInfo(long triggerTime, PendingIntent showIntent) {
796            mTriggerTime = triggerTime;
797            mShowIntent = showIntent;
798        }
799
800        /**
801         * Use the {@link #CREATOR}
802         * @hide
803         */
804        AlarmClockInfo(Parcel in) {
805            mTriggerTime = in.readLong();
806            mShowIntent = in.readParcelable(PendingIntent.class.getClassLoader());
807        }
808
809        /**
810         * Returns the time at which the alarm is going to trigger.
811         *
812         * This value is UTC wall clock time in milliseconds, as returned by
813         * {@link System#currentTimeMillis()} for example.
814         */
815        public long getTriggerTime() {
816            return mTriggerTime;
817        }
818
819        /**
820         * Returns an intent intent that can be used to show or edit details of the alarm clock in
821         * the application that scheduled it.
822         *
823         * <p class="note">Beware that any application can retrieve and send this intent,
824         * potentially with additional fields filled in. See
825         * {@link PendingIntent#send(android.content.Context, int, android.content.Intent)
826         * PendingIntent.send()} and {@link android.content.Intent#fillIn Intent.fillIn()}
827         * for details.
828         */
829        public PendingIntent getShowIntent() {
830            return mShowIntent;
831        }
832
833        @Override
834        public int describeContents() {
835            return 0;
836        }
837
838        @Override
839        public void writeToParcel(Parcel dest, int flags) {
840            dest.writeLong(mTriggerTime);
841            dest.writeParcelable(mShowIntent, flags);
842        }
843
844        public static final Creator<AlarmClockInfo> CREATOR = new Creator<AlarmClockInfo>() {
845            @Override
846            public AlarmClockInfo createFromParcel(Parcel in) {
847                return new AlarmClockInfo(in);
848            }
849
850            @Override
851            public AlarmClockInfo[] newArray(int size) {
852                return new AlarmClockInfo[size];
853            }
854        };
855    }
856}
857