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