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