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