• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.app;
18 
19 import android.Manifest;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.RequiresPermission;
24 import android.annotation.SdkConstant;
25 import android.annotation.SdkConstant.SdkConstantType;
26 import android.annotation.SystemApi;
27 import android.annotation.SystemService;
28 import android.annotation.TestApi;
29 import android.compat.annotation.ChangeId;
30 import android.compat.annotation.EnabledSince;
31 import android.compat.annotation.UnsupportedAppUsage;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.os.Build;
35 import android.os.Handler;
36 import android.os.HandlerExecutor;
37 import android.os.Parcel;
38 import android.os.Parcelable;
39 import android.os.RemoteException;
40 import android.os.WorkSource;
41 import android.text.TextUtils;
42 import android.util.Log;
43 import android.util.proto.ProtoOutputStream;
44 
45 import com.android.i18n.timezone.ZoneInfoDb;
46 
47 import java.lang.annotation.Retention;
48 import java.lang.annotation.RetentionPolicy;
49 import java.lang.ref.WeakReference;
50 import java.util.Objects;
51 import java.util.WeakHashMap;
52 import java.util.concurrent.Executor;
53 
54 /**
55  * This class provides access to the system alarm services.  These allow you
56  * to schedule your application to be run at some point in the future.  When
57  * an alarm goes off, the {@link Intent} that had been registered for it
58  * is broadcast by the system, automatically starting the target application
59  * if it is not already running.  Registered alarms are retained while the
60  * device is asleep (and can optionally wake the device up if they go off
61  * during that time), but will be cleared if it is turned off and rebooted.
62  *
63  * <p>The Alarm Manager holds a CPU wake lock as long as the alarm receiver's
64  * onReceive() method is executing. This guarantees that the phone will not sleep
65  * until you have finished handling the broadcast. Once onReceive() returns, the
66  * Alarm Manager releases this wake lock. This means that the phone will in some
67  * cases sleep as soon as your onReceive() method completes.  If your alarm receiver
68  * called {@link android.content.Context#startService Context.startService()}, it
69  * is possible that the phone will sleep before the requested service is launched.
70  * To prevent this, your BroadcastReceiver and Service will need to implement a
71  * separate wake lock policy to ensure that the phone continues running until the
72  * service becomes available.
73  *
74  * <p><b>Note: The Alarm Manager is intended for cases where you want to have
75  * your application code run at a specific time, even if your application is
76  * not currently running.  For normal timing operations (ticks, timeouts,
77  * etc) it is easier and much more efficient to use
78  * {@link android.os.Handler}.</b>
79  *
80  * <p class="caution"><strong>Note:</strong> Beginning with API 19
81  * ({@link android.os.Build.VERSION_CODES#KITKAT}) alarm delivery is inexact:
82  * the OS will shift alarms in order to minimize wakeups and battery use.  There are
83  * new APIs to support applications which need strict delivery guarantees; see
84  * {@link #setWindow(int, long, long, PendingIntent)} and
85  * {@link #setExact(int, long, PendingIntent)}.  Applications whose {@code targetSdkVersion}
86  * is earlier than API 19 will continue to see the previous behavior in which all
87  * alarms are delivered exactly when requested.
88  */
89 @SystemService(Context.ALARM_SERVICE)
90 public class AlarmManager {
91     private static final String TAG = "AlarmManager";
92 
93     /** @hide */
94     @IntDef(prefix = { "RTC", "ELAPSED" }, value = {
95             RTC_WAKEUP,
96             RTC,
97             ELAPSED_REALTIME_WAKEUP,
98             ELAPSED_REALTIME,
99     })
100     @Retention(RetentionPolicy.SOURCE)
101     public @interface AlarmType {}
102 
103     /**
104      * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
105      * (wall clock time in UTC), which will wake up the device when
106      * it goes off.
107      */
108     public static final int RTC_WAKEUP = 0;
109     /**
110      * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
111      * (wall clock time in UTC).  This alarm does not wake the
112      * device up; if it goes off while the device is asleep, it will not be
113      * delivered until the next time the device wakes up.
114      */
115     public static final int RTC = 1;
116     /**
117      * Alarm time in {@link android.os.SystemClock#elapsedRealtime
118      * SystemClock.elapsedRealtime()} (time since boot, including sleep),
119      * which will wake up the device when it goes off.
120      */
121     public static final int ELAPSED_REALTIME_WAKEUP = 2;
122     /**
123      * Alarm time in {@link android.os.SystemClock#elapsedRealtime
124      * SystemClock.elapsedRealtime()} (time since boot, including sleep).
125      * This alarm does not wake the device up; if it goes off while the device
126      * is asleep, it will not be delivered until the next time the device
127      * wakes up.
128      */
129     public static final int ELAPSED_REALTIME = 3;
130 
131     /**
132      * Broadcast Action: Sent after the value returned by
133      * {@link #getNextAlarmClock()} has changed.
134      *
135      * <p class="note">This is a protected intent that can only be sent by the system.
136      * It is only sent to registered receivers.</p>
137      */
138     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
139     public static final String ACTION_NEXT_ALARM_CLOCK_CHANGED =
140             "android.app.action.NEXT_ALARM_CLOCK_CHANGED";
141 
142     /**
143      * Broadcast Action: An app is granted the
144      * {@link android.Manifest.permission#SCHEDULE_EXACT_ALARM} permission.
145      *
146      * <p>When the user revokes the {@link android.Manifest.permission#SCHEDULE_EXACT_ALARM}
147      * permission, all alarms scheduled with
148      * {@link #setExact}, {@link #setExactAndAllowWhileIdle} and
149      * {@link #setAlarmClock(AlarmClockInfo, PendingIntent)} will be deleted.
150      *
151      * <p>When the user grants the {@link android.Manifest.permission#SCHEDULE_EXACT_ALARM},
152      * this broadcast will be sent. Applications can reschedule all the necessary alarms when
153      * receiving it.
154      *
155      * <p>This broadcast will <em>not</em> be sent when the user revokes the permission.
156      *
157      * <p><em>Note:</em>
158      * Applications are still required to check {@link #canScheduleExactAlarms()}
159      * before using the above APIs after receiving this broadcast,
160      * because it's possible that the permission is already revoked again by the time
161      * applications receive this broadcast.
162      *
163      * <p>This broadcast will be sent to both runtime receivers and manifest receivers.
164      *
165      * <p>This broadcast is sent as a foreground broadcast.
166      * See {@link android.content.Intent#FLAG_RECEIVER_FOREGROUND}.
167      *
168      * <p>When an application receives this broadcast, it's allowed to start a foreground service.
169      */
170     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
171     public static final String ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED =
172             "android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED";
173 
174     /** @hide */
175     @UnsupportedAppUsage
176     public static final long WINDOW_EXACT = 0;
177     /** @hide */
178     @UnsupportedAppUsage
179     public static final long WINDOW_HEURISTIC = -1;
180 
181     /**
182      * Flag for alarms: this is to be a stand-alone alarm, that should not be batched with
183      * other alarms.
184      * @hide
185      */
186     @UnsupportedAppUsage
187     public static final int FLAG_STANDALONE = 1<<0;
188 
189     /**
190      * Flag for alarms: this alarm would like to wake the device even if it is idle.  This
191      * is, for example, an alarm for an alarm clock.
192      * @hide
193      */
194     @UnsupportedAppUsage
195     public static final int FLAG_WAKE_FROM_IDLE = 1<<1;
196 
197     /**
198      * Flag for alarms: this alarm would like to still execute even if the device is
199      * idle.  This won't bring the device out of idle, just allow this specific alarm to
200      * run.  Note that this means the actual time this alarm goes off can be inconsistent
201      * with the time of non-allow-while-idle alarms (it could go earlier than the time
202      * requested by another alarm).
203      *
204      * @hide
205      */
206     public static final int FLAG_ALLOW_WHILE_IDLE = 1<<2;
207 
208     /**
209      * Flag for alarms: same as {@link #FLAG_ALLOW_WHILE_IDLE}, but doesn't have restrictions
210      * on how frequently it can be scheduled.  Only available (and automatically applied) to
211      * system alarms.
212      *
213      * @hide
214      */
215     @UnsupportedAppUsage
216     public static final int FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED = 1<<3;
217 
218     /**
219      * Flag for alarms: this alarm marks the point where we would like to come out of idle
220      * mode.  It may be moved by the alarm manager to match the first wake-from-idle alarm.
221      * Scheduling an alarm with this flag puts the alarm manager in to idle mode, where it
222      * avoids scheduling any further alarms until the marker alarm is executed.
223      * @hide
224      */
225     @UnsupportedAppUsage
226     public static final int FLAG_IDLE_UNTIL = 1<<4;
227 
228     /**
229      * Flag for alarms: Used to provide backwards compatibility for apps with targetSdkVersion less
230      * than {@link Build.VERSION_CODES#S}
231      * @hide
232      */
233     public static final int FLAG_ALLOW_WHILE_IDLE_COMPAT = 1 << 5;
234 
235     /**
236      * Flag for alarms: Used to mark prioritized alarms. These alarms will get to execute while idle
237      * and can be sent separately from other alarms that may be already due at the time.
238      * These alarms can be set via
239      * {@link #setPrioritized(int, long, long, String, Executor, OnAlarmListener)}
240      * @hide
241      */
242     public static final int FLAG_PRIORITIZE = 1 << 6;
243 
244     /**
245      * For apps targeting {@link Build.VERSION_CODES#S} or above, any APIs setting exact alarms,
246      * e.g. {@link #setExact(int, long, PendingIntent)},
247      * {@link #setAlarmClock(AlarmClockInfo, PendingIntent)} and others will require holding a new
248      * permission {@link Manifest.permission#SCHEDULE_EXACT_ALARM}
249      *
250      * @hide
251      */
252     @ChangeId
253     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
254     public static final long REQUIRE_EXACT_ALARM_PERMISSION = 171306433L;
255 
256     /**
257      * For apps targeting {@link Build.VERSION_CODES#S} or above, all inexact alarms will require
258      * to have a minimum window size, expected to be on the order of a few minutes.
259      *
260      * Practically, any alarms requiring smaller windows are the same as exact alarms and should use
261      * the corresponding APIs provided, like {@link #setExact(int, long, PendingIntent)}, et al.
262      *
263      * Inexact alarm with shorter windows specified will have their windows elongated by the system.
264      *
265      * @hide
266      */
267     @ChangeId
268     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
269     public static final long ENFORCE_MINIMUM_WINDOW_ON_INEXACT_ALARMS = 185199076L;
270 
271     @UnsupportedAppUsage
272     private final IAlarmManager mService;
273     private final Context mContext;
274     private final String mPackageName;
275     private final boolean mAlwaysExact;
276     private final int mTargetSdkVersion;
277     private final Handler mMainThreadHandler;
278 
279     /**
280      * Direct-notification alarms: the requester must be running continuously from the
281      * time the alarm is set to the time it is delivered, or delivery will fail.  Only
282      * one-shot alarms can be set using this mechanism, not repeating alarms.
283      */
284     public interface OnAlarmListener {
285         /**
286          * Callback method that is invoked by the system when the alarm time is reached.
287          */
onAlarm()288         public void onAlarm();
289     }
290 
291     final class ListenerWrapper extends IAlarmListener.Stub implements Runnable {
292         final OnAlarmListener mListener;
293         Executor mExecutor;
294         IAlarmCompleteListener mCompletion;
295 
ListenerWrapper(OnAlarmListener listener)296         public ListenerWrapper(OnAlarmListener listener) {
297             mListener = listener;
298         }
299 
setExecutor(Executor e)300         void setExecutor(Executor e) {
301             mExecutor = e;
302         }
303 
cancel()304         public void cancel() {
305             try {
306                 mService.remove(null, this);
307             } catch (RemoteException ex) {
308                 throw ex.rethrowFromSystemServer();
309             }
310         }
311 
312         @Override
doAlarm(IAlarmCompleteListener alarmManager)313         public void doAlarm(IAlarmCompleteListener alarmManager) {
314             mCompletion = alarmManager;
315 
316             mExecutor.execute(this);
317         }
318 
319         @Override
run()320         public void run() {
321             // Now deliver it to the app
322             try {
323                 mListener.onAlarm();
324             } finally {
325                 // No catch -- make sure to report completion to the system process,
326                 // but continue to allow the exception to crash the app.
327 
328                 try {
329                     mCompletion.alarmComplete(this);
330                 } catch (Exception e) {
331                     Log.e(TAG, "Unable to report completion to Alarm Manager!", e);
332                 }
333             }
334         }
335     }
336 
337     /**
338      * Tracking of the OnAlarmListener -> ListenerWrapper mapping, for cancel() support.
339      * An entry is guaranteed to stay in this map as long as its ListenerWrapper is held by the
340      * server.
341      *
342      * <p>Access is synchronized on the AlarmManager class object.
343      */
344     private static WeakHashMap<OnAlarmListener, WeakReference<ListenerWrapper>> sWrappers;
345 
346     /**
347      * package private on purpose
348      */
AlarmManager(IAlarmManager service, Context ctx)349     AlarmManager(IAlarmManager service, Context ctx) {
350         mService = service;
351 
352         mContext = ctx;
353         mPackageName = ctx.getPackageName();
354         mTargetSdkVersion = ctx.getApplicationInfo().targetSdkVersion;
355         mAlwaysExact = (mTargetSdkVersion < Build.VERSION_CODES.KITKAT);
356         mMainThreadHandler = new Handler(ctx.getMainLooper());
357     }
358 
legacyExactLength()359     private long legacyExactLength() {
360         return (mAlwaysExact ? WINDOW_EXACT : WINDOW_HEURISTIC);
361     }
362 
363     /**
364      * <p>Schedule an alarm.  <b>Note: for timing operations (ticks, timeouts,
365      * etc) it is easier and much more efficient to use {@link android.os.Handler}.</b>
366      * If there is already an alarm scheduled for the same IntentSender, that previous
367      * alarm will first be canceled.
368      *
369      * <p>If the stated trigger time is in the past, the alarm will be triggered
370      * immediately.  If there is already an alarm for this Intent
371      * scheduled (with the equality of two intents being defined by
372      * {@link Intent#filterEquals}), then it will be removed and replaced by
373      * this one.
374      *
375      * <p>
376      * The alarm is an Intent broadcast that goes to a broadcast receiver that
377      * you registered with {@link android.content.Context#registerReceiver}
378      * or through the &lt;receiver&gt; tag in an AndroidManifest.xml file.
379      *
380      * <p>
381      * Alarm intents are delivered with a data extra of type int called
382      * {@link Intent#EXTRA_ALARM_COUNT Intent.EXTRA_ALARM_COUNT} that indicates
383      * how many past alarm events have been accumulated into this intent
384      * broadcast.  Recurring alarms that have gone undelivered because the
385      * phone was asleep may have a count greater than one when delivered.
386      *
387      * <div class="note">
388      * <p>
389      * <b>Note:</b> Beginning in API 19, the trigger time passed to this method
390      * is treated as inexact: the alarm will not be delivered before this time, but
391      * may be deferred and delivered some time later.  The OS will use
392      * this policy in order to "batch" alarms together across the entire system,
393      * minimizing the number of times the device needs to "wake up" and minimizing
394      * battery use.  In general, alarms scheduled in the near future will not
395      * be deferred as long as alarms scheduled far in the future.
396      *
397      * <p>
398      * With the new batching policy, delivery ordering guarantees are not as
399      * strong as they were previously.  If the application sets multiple alarms,
400      * it is possible that these alarms' <em>actual</em> delivery ordering may not match
401      * the order of their <em>requested</em> delivery times.  If your application has
402      * strong ordering requirements there are other APIs that you can use to get
403      * the necessary behavior; see {@link #setWindow(int, long, long, PendingIntent)}
404      * and {@link #setExact(int, long, PendingIntent)}.
405      *
406      * <p>
407      * Applications whose {@code targetSdkVersion} is before API 19 will
408      * continue to get the previous alarm behavior: all of their scheduled alarms
409      * will be treated as exact.
410      * </div>
411      *
412      * @param type type of alarm.
413      * @param triggerAtMillis time in milliseconds that the alarm should go
414      * off, using the appropriate clock (depending on the alarm type).
415      * @param operation Action to perform when the alarm goes off;
416      * typically comes from {@link PendingIntent#getBroadcast
417      * IntentSender.getBroadcast()}.
418      *
419      * @see android.os.Handler
420      * @see #setExact
421      * @see #setRepeating
422      * @see #setWindow
423      * @see #cancel
424      * @see android.content.Context#sendBroadcast
425      * @see android.content.Context#registerReceiver
426      * @see android.content.Intent#filterEquals
427      * @see #ELAPSED_REALTIME
428      * @see #ELAPSED_REALTIME_WAKEUP
429      * @see #RTC
430      * @see #RTC_WAKEUP
431      */
set(@larmType int type, long triggerAtMillis, PendingIntent operation)432     public void set(@AlarmType int type, long triggerAtMillis, PendingIntent operation) {
433         setImpl(type, triggerAtMillis, legacyExactLength(), 0, 0, operation, null, null,
434                 (Handler) null, null, null);
435     }
436 
437     /**
438      * Direct callback version of {@link #set(int, long, PendingIntent)}.  Rather than
439      * supplying a PendingIntent to be sent when the alarm time is reached, this variant
440      * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
441      * <p>
442      * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
443      * invoked via the specified target Handler, or on the application's main looper
444      * if {@code null} is passed as the {@code targetHandler} parameter.
445      *
446      * @param type type of alarm.
447      * @param triggerAtMillis time in milliseconds that the alarm should go
448      *         off, using the appropriate clock (depending on the alarm type).
449      * @param tag string describing the alarm, used for logging and battery-use
450      *         attribution
451      * @param listener {@link OnAlarmListener} instance whose
452      *         {@link OnAlarmListener#onAlarm() onAlarm()} method will be
453      *         called when the alarm time is reached.  A given OnAlarmListener instance can
454      *         only be the target of a single pending alarm, just as a given PendingIntent
455      *         can only be used with one alarm at a time.
456      * @param targetHandler {@link Handler} on which to execute the listener's onAlarm()
457      *         callback, or {@code null} to run that callback on the main looper.
458      */
set(@larmType int type, long triggerAtMillis, String tag, OnAlarmListener listener, Handler targetHandler)459     public void set(@AlarmType int type, long triggerAtMillis, String tag, OnAlarmListener listener,
460             Handler targetHandler) {
461         setImpl(type, triggerAtMillis, legacyExactLength(), 0, 0, null, listener, tag,
462                 targetHandler, null, null);
463     }
464 
465     /**
466      * Schedule a repeating alarm.  <b>Note: for timing operations (ticks,
467      * timeouts, etc) it is easier and much more efficient to use
468      * {@link android.os.Handler}.</b>  If there is already an alarm scheduled
469      * for the same IntentSender, it will first be canceled.
470      *
471      * <p>Like {@link #set}, except you can also supply a period at which
472      * the alarm will automatically repeat.  This alarm continues
473      * repeating until explicitly removed with {@link #cancel}.  If the stated
474      * trigger time is in the past, the alarm will be triggered immediately, with an
475      * alarm count depending on how far in the past the trigger time is relative
476      * to the repeat interval.
477      *
478      * <p>If an alarm is delayed (by system sleep, for example, for non
479      * _WAKEUP alarm types), a skipped repeat will be delivered as soon as
480      * possible.  After that, future alarms will be delivered according to the
481      * original schedule; they do not drift over time.  For example, if you have
482      * set a recurring alarm for the top of every hour but the phone was asleep
483      * from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens,
484      * then the next alarm will be sent at 9:00.
485      *
486      * <p>If your application wants to allow the delivery times to drift in
487      * order to guarantee that at least a certain time interval always elapses
488      * between alarms, then the approach to take is to use one-time alarms,
489      * scheduling the next one yourself when handling each alarm delivery.
490      *
491      * <p class="note">
492      * <b>Note:</b> as of API 19, all repeating alarms are inexact.  If your
493      * application needs precise delivery times then it must use one-time
494      * exact alarms, rescheduling each time as described above. Legacy applications
495      * whose {@code targetSdkVersion} is earlier than API 19 will continue to have all
496      * of their alarms, including repeating alarms, treated as exact.
497      * <p>Apps targeting {@link Build.VERSION_CODES#S} will need to set the flag
498      * {@link PendingIntent#FLAG_MUTABLE} on the {@link PendingIntent} being used to set this alarm,
499      * if they want the alarm count to be supplied with the key {@link Intent#EXTRA_ALARM_COUNT}.
500      *
501      * @param type type of alarm.
502      * @param triggerAtMillis time in milliseconds that the alarm should first
503      * go off, using the appropriate clock (depending on the alarm type).
504      * @param intervalMillis interval in milliseconds between subsequent repeats
505      * of the alarm.
506      * @param operation Action to perform when the alarm goes off;
507      * typically comes from {@link PendingIntent#getBroadcast
508      * IntentSender.getBroadcast()}.
509      *
510      * @see android.os.Handler
511      * @see #set
512      * @see #setExact
513      * @see #setWindow
514      * @see #cancel
515      * @see android.content.Context#sendBroadcast
516      * @see android.content.Context#registerReceiver
517      * @see android.content.Intent#filterEquals
518      * @see #ELAPSED_REALTIME
519      * @see #ELAPSED_REALTIME_WAKEUP
520      * @see #RTC
521      * @see #RTC_WAKEUP
522      * @see Intent#EXTRA_ALARM_COUNT
523      */
setRepeating(@larmType int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)524     public void setRepeating(@AlarmType int type, long triggerAtMillis,
525             long intervalMillis, PendingIntent operation) {
526         setImpl(type, triggerAtMillis, legacyExactLength(), intervalMillis, 0, operation,
527                 null, null, (Handler) null, null, null);
528     }
529 
530     /**
531      * Schedule an alarm to be delivered within a given window of time.  This method
532      * is similar to {@link #set(int, long, PendingIntent)}, but allows the
533      * application to precisely control the degree to which its delivery might be
534      * adjusted by the OS. This method allows an application to take advantage of the
535      * battery optimizations that arise from delivery batching even when it has
536      * modest timeliness requirements for its alarms.
537      *
538      * <p>
539      * Note: Starting with API {@link Build.VERSION_CODES#S}, apps should not pass in a window of
540      * less than 10 minutes. The system will try its best to accommodate smaller windows if the
541      * alarm is supposed to fire in the near future, but there are no guarantees and the app should
542      * expect any window smaller than 10 minutes to get elongated to 10 minutes.
543      *
544      * <p>
545      * This method can also be used to achieve strict ordering guarantees among
546      * multiple alarms by ensuring that the windows requested for each alarm do
547      * not intersect.
548      *
549      * <p>
550      * When precise delivery is not required, applications should use the standard
551      * {@link #set(int, long, PendingIntent)} method.  This will give the OS the most
552      * flexibility to minimize wakeups and battery use.  For alarms that must be delivered
553      * at precisely-specified times with no acceptable variation, applications can use
554      * {@link #setExact(int, long, PendingIntent)}.
555      *
556      * @param type type of alarm.
557      * @param windowStartMillis The earliest time, in milliseconds, that the alarm should
558      *        be delivered, expressed in the appropriate clock's units (depending on the alarm
559      *        type).
560      * @param windowLengthMillis The length of the requested delivery window,
561      *        in milliseconds.  The alarm will be delivered no later than this many
562      *        milliseconds after {@code windowStartMillis}.  Note that this parameter
563      *        is a <i>duration,</i> not the timestamp of the end of the window.
564      * @param operation Action to perform when the alarm goes off;
565      *        typically comes from {@link PendingIntent#getBroadcast
566      *        IntentSender.getBroadcast()}.
567      *
568      * @see #set
569      * @see #setExact
570      * @see #setRepeating
571      * @see #cancel
572      * @see android.content.Context#sendBroadcast
573      * @see android.content.Context#registerReceiver
574      * @see android.content.Intent#filterEquals
575      * @see #ELAPSED_REALTIME
576      * @see #ELAPSED_REALTIME_WAKEUP
577      * @see #RTC
578      * @see #RTC_WAKEUP
579      */
setWindow(@larmType int type, long windowStartMillis, long windowLengthMillis, PendingIntent operation)580     public void setWindow(@AlarmType int type, long windowStartMillis, long windowLengthMillis,
581             PendingIntent operation) {
582         setImpl(type, windowStartMillis, windowLengthMillis, 0, 0, operation,
583                 null, null, (Handler) null, null, null);
584     }
585 
586     /**
587      * Direct callback version of {@link #setWindow(int, long, long, PendingIntent)}.  Rather
588      * than supplying a PendingIntent to be sent when the alarm time is reached, this variant
589      * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
590      * <p>
591      * The OnAlarmListener {@link OnAlarmListener#onAlarm() onAlarm()} method will be
592      * invoked via the specified target Handler, or on the application's main looper
593      * if {@code null} is passed as the {@code targetHandler} parameter.
594      *
595      * <p>
596      * Note: Starting with API {@link Build.VERSION_CODES#S}, apps should not pass in a window of
597      * less than 10 minutes. The system will try its best to accommodate smaller windows if the
598      * alarm is supposed to fire in the near future, but there are no guarantees and the app should
599      * expect any window smaller than 10 minutes to get elongated to 10 minutes.
600      *
601      * @see #setWindow(int, long, long, PendingIntent)
602      */
setWindow(@larmType int type, long windowStartMillis, long windowLengthMillis, String tag, OnAlarmListener listener, Handler targetHandler)603     public void setWindow(@AlarmType int type, long windowStartMillis, long windowLengthMillis,
604             String tag, OnAlarmListener listener, Handler targetHandler) {
605         setImpl(type, windowStartMillis, windowLengthMillis, 0, 0, null, listener, tag,
606                 targetHandler, null, null);
607     }
608 
609     /**
610      * Schedule an alarm that is prioritized by the system while the device is in power saving modes
611      * such as battery saver and device idle (doze).
612      *
613      * <p>
614      * Apps that use this are not guaranteed to get all alarms as requested during power saving
615      * modes, i.e. the system may still impose restrictions on how frequently these alarms will go
616      * off for a particular application, like requiring a certain minimum duration be elapsed
617      * between consecutive alarms. This duration will be normally be in the order of a few minutes.
618      *
619      * <p>
620      * When the system wakes up to deliver these alarms, it may not deliver any of the other pending
621      * alarms set earlier by the calling app, even the special ones set via
622      * {@link #setAndAllowWhileIdle(int, long, PendingIntent)} or
623      * {@link #setExactAndAllowWhileIdle(int, long, PendingIntent)}. So the caller should not
624      * expect these to arrive in any relative order to its other alarms.
625      *
626      * @param type type of alarm
627      * @param windowStartMillis The earliest time, in milliseconds, that the alarm should
628      *        be delivered, expressed in the appropriate clock's units (depending on the alarm
629      *        type).
630      * @param windowLengthMillis The length of the requested delivery window,
631      *        in milliseconds.  The alarm will be delivered no later than this many
632      *        milliseconds after {@code windowStartMillis}.  Note that this parameter
633      *        is a <i>duration,</i> not the timestamp of the end of the window.
634      * @param tag Optional. A string describing the alarm, used for logging and battery-use
635      *         attribution.
636      * @param listener {@link OnAlarmListener} instance whose
637      *         {@link OnAlarmListener#onAlarm() onAlarm()} method will be
638      *         called when the alarm time is reached.  A given OnAlarmListener instance can
639      *         only be the target of a single pending alarm, just as a given PendingIntent
640      *         can only be used with one alarm at a time.
641      * @param executor {@link Executor} on which to execute the listener's onAlarm()
642      *         callback.
643      * @hide
644      */
645     @SystemApi
646     @RequiresPermission(Manifest.permission.SCHEDULE_PRIORITIZED_ALARM)
setPrioritized(@larmType int type, long windowStartMillis, long windowLengthMillis, @Nullable String tag, @NonNull Executor executor, @NonNull OnAlarmListener listener)647     public void setPrioritized(@AlarmType int type, long windowStartMillis, long windowLengthMillis,
648             @Nullable String tag, @NonNull Executor executor, @NonNull OnAlarmListener listener) {
649         Objects.requireNonNull(executor);
650         Objects.requireNonNull(listener);
651         setImpl(type, windowStartMillis, windowLengthMillis, 0, FLAG_PRIORITIZE, null, listener,
652                 tag, executor, null, null);
653     }
654 
655     /**
656      * Schedule an alarm to be delivered precisely at the stated time.
657      *
658      * <p>
659      * This method is like {@link #set(int, long, PendingIntent)}, but does not permit
660      * the OS to adjust the delivery time.  The alarm will be delivered as nearly as
661      * possible to the requested trigger time.
662      *
663      * <p>
664      * <b>Note:</b> only alarms for which there is a strong demand for exact-time
665      * delivery (such as an alarm clock ringing at the requested time) should be
666      * scheduled as exact.  Applications are strongly discouraged from using exact
667      * alarms unnecessarily as they reduce the OS's ability to minimize battery use.
668      *
669      * <p class="note"><strong>Note:</strong>
670      * Starting with {@link Build.VERSION_CODES#S}, apps targeting SDK level 31 or higher
671      * need to request the
672      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM} permission to use this
673      * API, unless the app is exempt from battery restrictions.
674      * The user and the system can revoke this permission via the special app access screen in
675      * Settings.
676      *
677      * <p class="note"><strong>Note:</strong>
678      * Exact alarms should only be used for user-facing features.
679      * For more details, see <a
680      * href="{@docRoot}about/versions/12/behavior-changes-12#exact-alarm-permission">
681      * Exact alarm permission</a>.
682      *
683      * @param type type of alarm.
684      * @param triggerAtMillis time in milliseconds that the alarm should go
685      *        off, using the appropriate clock (depending on the alarm type).
686      * @param operation Action to perform when the alarm goes off;
687      *        typically comes from {@link PendingIntent#getBroadcast
688      *        IntentSender.getBroadcast()}.
689      *
690      * @see #set
691      * @see #setRepeating
692      * @see #setWindow
693      * @see #cancel
694      * @see android.content.Context#sendBroadcast
695      * @see android.content.Context#registerReceiver
696      * @see android.content.Intent#filterEquals
697      * @see #ELAPSED_REALTIME
698      * @see #ELAPSED_REALTIME_WAKEUP
699      * @see #RTC
700      * @see #RTC_WAKEUP
701      * @see Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM
702      */
703     @RequiresPermission(value = Manifest.permission.SCHEDULE_EXACT_ALARM, conditional = true)
setExact(@larmType int type, long triggerAtMillis, PendingIntent operation)704     public void setExact(@AlarmType int type, long triggerAtMillis, PendingIntent operation) {
705         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, operation, null, null, (Handler) null,
706                 null, null);
707     }
708 
709     /**
710      * Direct callback version of {@link #setExact(int, long, PendingIntent)}.  Rather
711      * than supplying a PendingIntent to be sent when the alarm time is reached, this variant
712      * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
713      * <p>
714      * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
715      * invoked via the specified target Handler, or on the application's main looper
716      * if {@code null} is passed as the {@code targetHandler} parameter.
717      *
718      * <p class="note"><strong>Note:</strong>
719      * Starting with {@link Build.VERSION_CODES#S}, apps targeting SDK level 31 or higher
720      * need to request the
721      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM} permission to use this
722      * API, unless the app is exempt from battery restrictions.
723      * The user and the system can revoke this permission via the special app access screen in
724      * Settings.
725      *
726      * <p class="note"><strong>Note:</strong>
727      * Exact alarms should only be used for user-facing features.
728      * For more details, see <a
729      * href="{@docRoot}about/versions/12/behavior-changes-12#exact-alarm-permission">
730      * Exact alarm permission</a>.
731      *
732      * @see Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM
733      */
734     @RequiresPermission(value = Manifest.permission.SCHEDULE_EXACT_ALARM, conditional = true)
setExact(@larmType int type, long triggerAtMillis, String tag, OnAlarmListener listener, Handler targetHandler)735     public void setExact(@AlarmType int type, long triggerAtMillis, String tag,
736             OnAlarmListener listener, Handler targetHandler) {
737         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, null, listener, tag,
738                 targetHandler, null, null);
739     }
740 
741     /**
742      * Schedule an idle-until alarm, which will keep the alarm manager idle until
743      * the given time.
744      * @hide
745      */
setIdleUntil(@larmType int type, long triggerAtMillis, String tag, OnAlarmListener listener, Handler targetHandler)746     public void setIdleUntil(@AlarmType int type, long triggerAtMillis, String tag,
747             OnAlarmListener listener, Handler targetHandler) {
748         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_IDLE_UNTIL, null,
749                 listener, tag, targetHandler, null, null);
750     }
751 
752     /**
753      * Schedule an alarm that represents an alarm clock, which will be used to notify the user
754      * when it goes off.  The expectation is that when this alarm triggers, the application will
755      * further wake up the device to tell the user about the alarm -- turning on the screen,
756      * playing a sound, vibrating, etc.  As such, the system will typically also use the
757      * information supplied here to tell the user about this upcoming alarm if appropriate.
758      *
759      * <p>Due to the nature of this kind of alarm, similar to {@link #setExactAndAllowWhileIdle},
760      * these alarms will be allowed to trigger even if the system is in a low-power idle
761      * (a.k.a. doze) mode.  The system may also do some prep-work when it sees that such an
762      * alarm coming up, to reduce the amount of background work that could happen if this
763      * causes the device to fully wake up -- this is to avoid situations such as a large number
764      * of devices having an alarm set at the same time in the morning, all waking up at that
765      * time and suddenly swamping the network with pending background work.  As such, these
766      * types of alarms can be extremely expensive on battery use and should only be used for
767      * their intended purpose.</p>
768      *
769      * <p>
770      * This method is like {@link #setExact(int, long, PendingIntent)}, but implies
771      * {@link #RTC_WAKEUP}.
772      *
773      * <p class="note"><strong>Note:</strong>
774      * Starting with {@link Build.VERSION_CODES#S}, apps targeting SDK level 31 or higher
775      * need to request the
776      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM} permission to use this
777      * API.
778      * The user and the system can revoke this permission via the special app access screen in
779      * Settings.
780      *
781      * <p class="note"><strong>Note:</strong>
782      * Exact alarms should only be used for user-facing features.
783      * For more details, see <a
784      * href="{@docRoot}about/versions/12/behavior-changes-12#exact-alarm-permission">
785      * Exact alarm permission</a>.
786      *
787      * <p>Alarms scheduled via this API
788      * will be allowed to start a foreground service even if the app is in the background.
789      *
790      * @param info
791      * @param operation Action to perform when the alarm goes off;
792      *        typically comes from {@link PendingIntent#getBroadcast
793      *        IntentSender.getBroadcast()}.
794      *
795      * @see #set
796      * @see #setRepeating
797      * @see #setWindow
798      * @see #setExact
799      * @see #cancel
800      * @see #getNextAlarmClock()
801      * @see android.content.Context#sendBroadcast
802      * @see android.content.Context#registerReceiver
803      * @see android.content.Intent#filterEquals
804      * @see Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM
805      */
806     @RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
setAlarmClock(AlarmClockInfo info, PendingIntent operation)807     public void setAlarmClock(AlarmClockInfo info, PendingIntent operation) {
808         setImpl(RTC_WAKEUP, info.getTriggerTime(), WINDOW_EXACT, 0, 0, operation,
809                 null, null, (Handler) null, null, info);
810     }
811 
812     /** @hide */
813     @SystemApi
814     @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
set(@larmType int type, long triggerAtMillis, long windowMillis, long intervalMillis, PendingIntent operation, WorkSource workSource)815     public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
816             long intervalMillis, PendingIntent operation, WorkSource workSource) {
817         setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, operation, null, null,
818                 (Handler) null, workSource, null);
819     }
820 
821     /**
822      * Direct callback version of {@link #set(int, long, long, long, PendingIntent, WorkSource)}.
823      * Note that repeating alarms must use the PendingIntent variant, not an OnAlarmListener.
824      * <p>
825      * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
826      * invoked via the specified target Handler, or on the application's main looper
827      * if {@code null} is passed as the {@code targetHandler} parameter.
828      *
829      * @hide
830      */
831     @UnsupportedAppUsage
set(@larmType int type, long triggerAtMillis, long windowMillis, long intervalMillis, String tag, OnAlarmListener listener, Handler targetHandler, WorkSource workSource)832     public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
833             long intervalMillis, String tag, OnAlarmListener listener, Handler targetHandler,
834             WorkSource workSource) {
835         setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, null, listener, tag,
836                 targetHandler, workSource, null);
837     }
838 
839     /**
840      * Direct callback version of {@link #set(int, long, long, long, PendingIntent, WorkSource)}.
841      * Note that repeating alarms must use the PendingIntent variant, not an OnAlarmListener.
842      * <p>
843      * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
844      * invoked via the specified target Handler, or on the application's main looper
845      * if {@code null} is passed as the {@code targetHandler} parameter.
846      *
847      * @hide
848      */
849     @SystemApi
850     @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
set(@larmType int type, long triggerAtMillis, long windowMillis, long intervalMillis, OnAlarmListener listener, Handler targetHandler, WorkSource workSource)851     public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
852             long intervalMillis, OnAlarmListener listener, Handler targetHandler,
853             WorkSource workSource) {
854         setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, null, listener, null,
855                 targetHandler, workSource, null);
856     }
857 
858     /**
859      * Exact version of {@link #set(int, long, long, long, OnAlarmListener, Handler, WorkSource)}.
860      * This equivalent to calling the aforementioned API with {@code windowMillis} and
861      * {@code intervalMillis} set to 0.
862      * One subtle difference is that this API requires {@code workSource} to be non-null. If you
863      * don't want to attribute this alarm to another app for battery consumption, you should use
864      * {@link #setExact(int, long, String, OnAlarmListener, Handler)} instead.
865      *
866      * <p>
867      * Note that using this API requires you to hold
868      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM}, unless you are on the system's power
869      * allowlist. This can be set, for example, by marking the app as {@code <allow-in-power-save>}
870      * within the system config.
871      *
872      * @param type            type of alarm
873      * @param triggerAtMillis The exact time in milliseconds, that the alarm should be delivered,
874      *                        expressed in the appropriate clock's units (depending on the alarm
875      *                        type).
876      * @param listener        {@link OnAlarmListener} instance whose
877      *                        {@link OnAlarmListener#onAlarm() onAlarm()} method will be called when
878      *                        the alarm time is reached.
879      * @param executor        The {@link Executor} on which to execute the listener's onAlarm()
880      *                        callback.
881      * @param tag             Optional. A string tag used to identify this alarm in logs and
882      *                        battery-attribution.
883      * @param workSource      A {@link WorkSource} object to attribute this alarm to the app that
884      *                        requested this work.
885      * @hide
886      */
887     @SystemApi
888     @RequiresPermission(allOf = {
889             Manifest.permission.UPDATE_DEVICE_STATS,
890             Manifest.permission.SCHEDULE_EXACT_ALARM}, conditional = true)
setExact(@larmType int type, long triggerAtMillis, @Nullable String tag, @NonNull Executor executor, @NonNull WorkSource workSource, @NonNull OnAlarmListener listener)891     public void setExact(@AlarmType int type, long triggerAtMillis, @Nullable String tag,
892             @NonNull Executor executor, @NonNull WorkSource workSource,
893             @NonNull OnAlarmListener listener) {
894         Objects.requireNonNull(executor);
895         Objects.requireNonNull(workSource);
896         Objects.requireNonNull(listener);
897         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, null, listener, tag, executor,
898                 workSource, null);
899     }
900 
901 
setImpl(@larmType int type, long triggerAtMillis, long windowMillis, long intervalMillis, int flags, PendingIntent operation, final OnAlarmListener listener, String listenerTag, Handler targetHandler, WorkSource workSource, AlarmClockInfo alarmClock)902     private void setImpl(@AlarmType int type, long triggerAtMillis, long windowMillis,
903             long intervalMillis, int flags, PendingIntent operation, final OnAlarmListener listener,
904             String listenerTag, Handler targetHandler, WorkSource workSource,
905             AlarmClockInfo alarmClock) {
906         final Handler handlerToUse = (targetHandler != null) ? targetHandler : mMainThreadHandler;
907         setImpl(type, triggerAtMillis, windowMillis, intervalMillis, flags, operation, listener,
908                 listenerTag, new HandlerExecutor(handlerToUse), workSource, alarmClock);
909     }
910 
setImpl(@larmType int type, long triggerAtMillis, long windowMillis, long intervalMillis, int flags, PendingIntent operation, final OnAlarmListener listener, String listenerTag, Executor targetExecutor, WorkSource workSource, AlarmClockInfo alarmClock)911     private void setImpl(@AlarmType int type, long triggerAtMillis, long windowMillis,
912             long intervalMillis, int flags, PendingIntent operation, final OnAlarmListener listener,
913             String listenerTag, Executor targetExecutor, WorkSource workSource,
914             AlarmClockInfo alarmClock) {
915         if (triggerAtMillis < 0) {
916             /* NOTYET
917             if (mAlwaysExact) {
918                 // Fatal error for KLP+ apps to use negative trigger times
919                 throw new IllegalArgumentException("Invalid alarm trigger time "
920                         + triggerAtMillis);
921             }
922             */
923             triggerAtMillis = 0;
924         }
925 
926         ListenerWrapper recipientWrapper = null;
927         if (listener != null) {
928             synchronized (AlarmManager.class) {
929                 if (sWrappers == null) {
930                     sWrappers = new WeakHashMap<>();
931                 }
932 
933                 final WeakReference<ListenerWrapper> weakRef = sWrappers.get(listener);
934                 if (weakRef != null) {
935                     recipientWrapper = weakRef.get();
936                 }
937                 // no existing wrapper => build a new one
938                 if (recipientWrapper == null) {
939                     recipientWrapper = new ListenerWrapper(listener);
940                     sWrappers.put(listener, new WeakReference<>(recipientWrapper));
941                 }
942             }
943             recipientWrapper.setExecutor(targetExecutor);
944         }
945 
946         try {
947             mService.set(mPackageName, type, triggerAtMillis, windowMillis, intervalMillis, flags,
948                     operation, recipientWrapper, listenerTag, workSource, alarmClock);
949         } catch (RemoteException ex) {
950             throw ex.rethrowFromSystemServer();
951         }
952     }
953 
954     /**
955      * Available inexact recurrence interval recognized by
956      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
957      * when running on Android prior to API 19.
958      */
959     public static final long INTERVAL_FIFTEEN_MINUTES = 15 * 60 * 1000;
960 
961     /**
962      * Available inexact recurrence interval recognized by
963      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
964      * when running on Android prior to API 19.
965      */
966     public static final long INTERVAL_HALF_HOUR = 2*INTERVAL_FIFTEEN_MINUTES;
967 
968     /**
969      * Available inexact recurrence interval recognized by
970      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
971      * when running on Android prior to API 19.
972      */
973     public static final long INTERVAL_HOUR = 2*INTERVAL_HALF_HOUR;
974 
975     /**
976      * Available inexact recurrence interval recognized by
977      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
978      * when running on Android prior to API 19.
979      */
980     public static final long INTERVAL_HALF_DAY = 12*INTERVAL_HOUR;
981 
982     /**
983      * Available inexact recurrence interval recognized by
984      * {@link #setInexactRepeating(int, long, long, PendingIntent)}
985      * when running on Android prior to API 19.
986      */
987     public static final long INTERVAL_DAY = 2*INTERVAL_HALF_DAY;
988 
989     /**
990      * Schedule a repeating alarm that has inexact trigger time requirements;
991      * for example, an alarm that repeats every hour, but not necessarily at
992      * the top of every hour.  These alarms are more power-efficient than
993      * the strict recurrences traditionally supplied by {@link #setRepeating}, since the
994      * system can adjust alarms' delivery times to cause them to fire simultaneously,
995      * avoiding waking the device from sleep more than necessary.
996      *
997      * <p>Your alarm's first trigger will not be before the requested time,
998      * but it might not occur for almost a full interval after that time.  In
999      * addition, while the overall period of the repeating alarm will be as
1000      * requested, the time between any two successive firings of the alarm
1001      * may vary.  If your application demands very low jitter, use
1002      * one-shot alarms with an appropriate window instead; see {@link
1003      * #setWindow(int, long, long, PendingIntent)} and
1004      * {@link #setExact(int, long, PendingIntent)}.
1005      *
1006      * <p class="note">
1007      * As of API 19, all repeating alarms are inexact.  Because this method has
1008      * been available since API 3, your application can safely call it and be
1009      * assured that it will get similar behavior on both current and older versions
1010      * of Android.
1011      * <p>Apps targeting {@link Build.VERSION_CODES#S} will need to set the flag
1012      * {@link PendingIntent#FLAG_MUTABLE} on the {@link PendingIntent} being used to set this alarm,
1013      * if they want the alarm count to be supplied with the key {@link Intent#EXTRA_ALARM_COUNT}.
1014      *
1015      * @param type type of alarm.
1016      * @param triggerAtMillis time in milliseconds that the alarm should first
1017      * go off, using the appropriate clock (depending on the alarm type).  This
1018      * is inexact: the alarm will not fire before this time, but there may be a
1019      * delay of almost an entire alarm interval before the first invocation of
1020      * the alarm.
1021      * @param intervalMillis interval in milliseconds between subsequent repeats
1022      * of the alarm.  Prior to API 19, if this is one of INTERVAL_FIFTEEN_MINUTES,
1023      * INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY
1024      * then the alarm will be phase-aligned with other alarms to reduce the
1025      * number of wakeups.  Otherwise, the alarm will be set as though the
1026      * application had called {@link #setRepeating}.  As of API 19, all repeating
1027      * alarms will be inexact and subject to batching with other alarms regardless
1028      * of their stated repeat interval.
1029      * @param operation Action to perform when the alarm goes off;
1030      * typically comes from {@link PendingIntent#getBroadcast
1031      * IntentSender.getBroadcast()}.
1032      *
1033      * @see android.os.Handler
1034      * @see #set
1035      * @see #cancel
1036      * @see android.content.Context#sendBroadcast
1037      * @see android.content.Context#registerReceiver
1038      * @see android.content.Intent#filterEquals
1039      * @see #ELAPSED_REALTIME
1040      * @see #ELAPSED_REALTIME_WAKEUP
1041      * @see #RTC
1042      * @see #RTC_WAKEUP
1043      * @see #INTERVAL_FIFTEEN_MINUTES
1044      * @see #INTERVAL_HALF_HOUR
1045      * @see #INTERVAL_HOUR
1046      * @see #INTERVAL_HALF_DAY
1047      * @see #INTERVAL_DAY
1048      * @see Intent#EXTRA_ALARM_COUNT
1049      */
setInexactRepeating(@larmType int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)1050     public void setInexactRepeating(@AlarmType int type, long triggerAtMillis,
1051             long intervalMillis, PendingIntent operation) {
1052         setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, intervalMillis, 0, operation, null,
1053                 null, (Handler) null, null, null);
1054     }
1055 
1056     /**
1057      * Like {@link #set(int, long, PendingIntent)}, but this alarm will be allowed to execute
1058      * even when the system is in low-power idle (a.k.a. doze) modes.  This type of alarm must
1059      * <b>only</b> be used for situations where it is actually required that the alarm go off while
1060      * in idle -- a reasonable example would be for a calendar notification that should make a
1061      * sound so the user is aware of it.  When the alarm is dispatched, the app will also be
1062      * added to the system's temporary power exemption list for approximately 10 seconds to allow
1063      * that application to acquire further wake locks in which to complete its work.</p>
1064      *
1065      * <p>These alarms can significantly impact the power use
1066      * of the device when idle (and thus cause significant battery blame to the app scheduling
1067      * them), so they should be used with care.  To reduce abuse, there are restrictions on how
1068      * frequently these alarms will go off for a particular application.
1069      * Under normal system operation, it will not dispatch these
1070      * alarms more than about every minute (at which point every such pending alarm is
1071      * dispatched); when in low-power idle modes this duration may be significantly longer,
1072      * such as 15 minutes.</p>
1073      *
1074      * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
1075      * out of order with any other alarms, even those from the same app.  This will clearly happen
1076      * when the device is idle (since this alarm can go off while idle, when any other alarms
1077      * from the app will be held until later), but may also happen even when not idle.</p>
1078      *
1079      * <p>Regardless of the app's target SDK version, this call always allows batching of the
1080      * alarm.</p>
1081      *
1082      * @param type type of alarm.
1083      * @param triggerAtMillis time in milliseconds that the alarm should go
1084      * off, using the appropriate clock (depending on the alarm type).
1085      * @param operation Action to perform when the alarm goes off;
1086      * typically comes from {@link PendingIntent#getBroadcast
1087      * IntentSender.getBroadcast()}.
1088      *
1089      * @see #set(int, long, PendingIntent)
1090      * @see #setExactAndAllowWhileIdle
1091      * @see #cancel
1092      * @see android.content.Context#sendBroadcast
1093      * @see android.content.Context#registerReceiver
1094      * @see android.content.Intent#filterEquals
1095      * @see #ELAPSED_REALTIME
1096      * @see #ELAPSED_REALTIME_WAKEUP
1097      * @see #RTC
1098      * @see #RTC_WAKEUP
1099      */
setAndAllowWhileIdle(@larmType int type, long triggerAtMillis, PendingIntent operation)1100     public void setAndAllowWhileIdle(@AlarmType int type, long triggerAtMillis,
1101             PendingIntent operation) {
1102         setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, 0, FLAG_ALLOW_WHILE_IDLE,
1103                 operation, null, null, (Handler) null, null, null);
1104     }
1105 
1106     /**
1107      * Like {@link #setExact(int, long, PendingIntent)}, but this alarm will be allowed to execute
1108      * even when the system is in low-power idle modes.  If you don't need exact scheduling of
1109      * the alarm but still need to execute while idle, consider using
1110      * {@link #setAndAllowWhileIdle}.  This type of alarm must <b>only</b>
1111      * be used for situations where it is actually required that the alarm go off while in
1112      * idle -- a reasonable example would be for a calendar notification that should make a
1113      * sound so the user is aware of it.  When the alarm is dispatched, the app will also be
1114      * added to the system's temporary power exemption list for approximately 10 seconds to allow
1115      * that application to acquire further wake locks in which to complete its work.</p>
1116      *
1117      * <p>These alarms can significantly impact the power use
1118      * of the device when idle (and thus cause significant battery blame to the app scheduling
1119      * them), so they should be used with care.  To reduce abuse, there are restrictions on how
1120      * frequently these alarms will go off for a particular application.
1121      * Under normal system operation, it will not dispatch these
1122      * alarms more than about every minute (at which point every such pending alarm is
1123      * dispatched); when in low-power idle modes this duration may be significantly longer,
1124      * such as 15 minutes.</p>
1125      *
1126      * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
1127      * out of order with any other alarms, even those from the same app.  This will clearly happen
1128      * when the device is idle (since this alarm can go off while idle, when any other alarms
1129      * from the app will be held until later), but may also happen even when not idle.
1130      * Note that the OS will allow itself more flexibility for scheduling these alarms than
1131      * regular exact alarms, since the application has opted into this behavior.  When the
1132      * device is idle it may take even more liberties with scheduling in order to optimize
1133      * for battery life.</p>
1134      *
1135      * <p class="note"><strong>Note:</strong>
1136      * Starting with {@link Build.VERSION_CODES#S}, apps targeting SDK level 31 or higher
1137      * need to request the
1138      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM} permission to use this
1139      * API, unless the app is exempt from battery restrictions.
1140      * The user and the system can revoke this permission via the special app access screen in
1141      * Settings.
1142      *
1143      * <p class="note"><strong>Note:</strong>
1144      * Exact alarms should only be used for user-facing features.
1145      * For more details, see <a
1146      * href="{@docRoot}about/versions/12/behavior-changes-12#exact-alarm-permission">
1147      * Exact alarm permission</a>.
1148      *
1149      * <p>Alarms scheduled via this API
1150      * will be allowed to start a foreground service even if the app is in the background.
1151      *
1152      * @param type type of alarm.
1153      * @param triggerAtMillis time in milliseconds that the alarm should go
1154      *        off, using the appropriate clock (depending on the alarm type).
1155      * @param operation Action to perform when the alarm goes off;
1156      *        typically comes from {@link PendingIntent#getBroadcast
1157      *        IntentSender.getBroadcast()}.
1158      *
1159      * @see #set
1160      * @see #setRepeating
1161      * @see #setWindow
1162      * @see #cancel
1163      * @see android.content.Context#sendBroadcast
1164      * @see android.content.Context#registerReceiver
1165      * @see android.content.Intent#filterEquals
1166      * @see #ELAPSED_REALTIME
1167      * @see #ELAPSED_REALTIME_WAKEUP
1168      * @see #RTC
1169      * @see #RTC_WAKEUP
1170      * @see Manifest.permission#SCHEDULE_EXACT_ALARM SCHEDULE_EXACT_ALARM
1171      */
1172     @RequiresPermission(value = Manifest.permission.SCHEDULE_EXACT_ALARM, conditional = true)
setExactAndAllowWhileIdle(@larmType int type, long triggerAtMillis, PendingIntent operation)1173     public void setExactAndAllowWhileIdle(@AlarmType int type, long triggerAtMillis,
1174             PendingIntent operation) {
1175         setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_ALLOW_WHILE_IDLE, operation,
1176                 null, null, (Handler) null, null, null);
1177     }
1178 
1179     /**
1180      * Remove any alarms with a matching {@link Intent}.
1181      * Any alarm, of any type, whose Intent matches this one (as defined by
1182      * {@link Intent#filterEquals}), will be canceled.
1183      *
1184      * @param operation IntentSender which matches a previously added
1185      * IntentSender. This parameter must not be {@code null}.
1186      *
1187      * @see #set
1188      */
cancel(PendingIntent operation)1189     public void cancel(PendingIntent operation) {
1190         if (operation == null) {
1191             final String msg = "cancel() called with a null PendingIntent";
1192             if (mTargetSdkVersion >= Build.VERSION_CODES.N) {
1193                 throw new NullPointerException(msg);
1194             } else {
1195                 Log.e(TAG, msg);
1196                 return;
1197             }
1198         }
1199 
1200         try {
1201             mService.remove(operation, null);
1202         } catch (RemoteException ex) {
1203             throw ex.rethrowFromSystemServer();
1204         }
1205     }
1206 
1207     /**
1208      * Remove any alarm scheduled to be delivered to the given {@link OnAlarmListener}.
1209      *
1210      * @param listener OnAlarmListener instance that is the target of a currently-set alarm.
1211      */
cancel(OnAlarmListener listener)1212     public void cancel(OnAlarmListener listener) {
1213         if (listener == null) {
1214             throw new NullPointerException("cancel() called with a null OnAlarmListener");
1215         }
1216 
1217         ListenerWrapper wrapper = null;
1218         synchronized (AlarmManager.class) {
1219             if (sWrappers != null) {
1220                 final WeakReference<ListenerWrapper> weakRef = sWrappers.get(listener);
1221                 if (weakRef != null) {
1222                     wrapper = weakRef.get();
1223                 }
1224             }
1225         }
1226 
1227         if (wrapper == null) {
1228             Log.w(TAG, "Unrecognized alarm listener " + listener);
1229             return;
1230         }
1231 
1232         wrapper.cancel();
1233     }
1234 
1235     /**
1236      * Set the system wall clock time.
1237      * Requires the permission android.permission.SET_TIME.
1238      *
1239      * @param millis time in milliseconds since the Epoch
1240      */
1241     @RequiresPermission(android.Manifest.permission.SET_TIME)
setTime(long millis)1242     public void setTime(long millis) {
1243         try {
1244             mService.setTime(millis);
1245         } catch (RemoteException ex) {
1246             throw ex.rethrowFromSystemServer();
1247         }
1248     }
1249 
1250     /**
1251      * Sets the system's persistent default time zone. This is the time zone for all apps, even
1252      * after a reboot. Use {@link java.util.TimeZone#setDefault} if you just want to change the
1253      * time zone within your app, and even then prefer to pass an explicit
1254      * {@link java.util.TimeZone} to APIs that require it rather than changing the time zone for
1255      * all threads.
1256      *
1257      * <p> On android M and above, it is an error to pass in a non-Olson timezone to this
1258      * function. Note that this is a bad idea on all Android releases because POSIX and
1259      * the {@code TimeZone} class have opposite interpretations of {@code '+'} and {@code '-'}
1260      * in the same non-Olson ID.
1261      *
1262      * @param timeZone one of the Olson ids from the list returned by
1263      *     {@link java.util.TimeZone#getAvailableIDs}
1264      */
1265     @RequiresPermission(android.Manifest.permission.SET_TIME_ZONE)
setTimeZone(String timeZone)1266     public void setTimeZone(String timeZone) {
1267         if (TextUtils.isEmpty(timeZone)) {
1268             return;
1269         }
1270 
1271         // Reject this timezone if it isn't an Olson zone we recognize.
1272         if (mTargetSdkVersion >= Build.VERSION_CODES.M) {
1273             boolean hasTimeZone = ZoneInfoDb.getInstance().hasTimeZone(timeZone);
1274             if (!hasTimeZone) {
1275                 throw new IllegalArgumentException("Timezone: " + timeZone + " is not an Olson ID");
1276             }
1277         }
1278 
1279         try {
1280             mService.setTimeZone(timeZone);
1281         } catch (RemoteException ex) {
1282             throw ex.rethrowFromSystemServer();
1283         }
1284     }
1285 
1286     /** @hide */
getNextWakeFromIdleTime()1287     public long getNextWakeFromIdleTime() {
1288         try {
1289             return mService.getNextWakeFromIdleTime();
1290         } catch (RemoteException ex) {
1291             throw ex.rethrowFromSystemServer();
1292         }
1293     }
1294 
1295     /**
1296      * Called to check if the caller can schedule exact alarms.
1297      * Your app schedules exact alarms when it calls any of the {@code setExact...} or
1298      * {@link #setAlarmClock(AlarmClockInfo, PendingIntent) setAlarmClock} API methods.
1299      * <p>
1300      * Apps targeting {@link Build.VERSION_CODES#S} or higher can schedule exact alarms only if they
1301      * have the {@link Manifest.permission#SCHEDULE_EXACT_ALARM} permission or they are on the
1302      * device's power-save exemption list.
1303      * These apps can also
1304      * start {@link android.provider.Settings#ACTION_REQUEST_SCHEDULE_EXACT_ALARM} to
1305      * request this permission from the user.
1306      * <p>
1307      * Apps targeting lower sdk versions, can always schedule exact alarms.
1308      *
1309      * @return {@code true} if the caller can schedule exact alarms, {@code false} otherwise.
1310      * @see android.provider.Settings#ACTION_REQUEST_SCHEDULE_EXACT_ALARM
1311      * @see #setExact(int, long, PendingIntent)
1312      * @see #setExactAndAllowWhileIdle(int, long, PendingIntent)
1313      * @see #setAlarmClock(AlarmClockInfo, PendingIntent)
1314      * @see android.os.PowerManager#isIgnoringBatteryOptimizations(String)
1315      */
canScheduleExactAlarms()1316     public boolean canScheduleExactAlarms() {
1317         try {
1318             return mService.canScheduleExactAlarms(mContext.getOpPackageName());
1319         } catch (RemoteException re) {
1320             throw re.rethrowFromSystemServer();
1321         }
1322     }
1323 
1324     /**
1325      * Called to check if the given package in the given user has the permission
1326      * {@link Manifest.permission#SCHEDULE_EXACT_ALARM}.
1327      *
1328      * <p><em>Note: This is only for use by system components.</em>
1329      *
1330      * @hide
1331      */
1332     @TestApi
hasScheduleExactAlarm(@onNull String packageName, int userId)1333     public boolean hasScheduleExactAlarm(@NonNull String packageName, int userId) {
1334         try {
1335             return mService.hasScheduleExactAlarm(packageName, userId);
1336         } catch (RemoteException re) {
1337             throw re.rethrowFromSystemServer();
1338         }
1339     }
1340 
1341     /**
1342      * Gets information about the next alarm clock currently scheduled.
1343      *
1344      * The alarm clocks considered are those scheduled by any application
1345      * using the {@link #setAlarmClock} method.
1346      *
1347      * @return An {@link AlarmClockInfo} object describing the next upcoming alarm
1348      *   clock event that will occur.  If there are no alarm clock events currently
1349      *   scheduled, this method will return {@code null}.
1350      *
1351      * @see #setAlarmClock
1352      * @see AlarmClockInfo
1353      * @see #ACTION_NEXT_ALARM_CLOCK_CHANGED
1354      */
getNextAlarmClock()1355     public AlarmClockInfo getNextAlarmClock() {
1356         return getNextAlarmClock(mContext.getUserId());
1357     }
1358 
1359     /**
1360      * Gets information about the next alarm clock currently scheduled.
1361      *
1362      * The alarm clocks considered are those scheduled by any application
1363      * using the {@link #setAlarmClock} method within the given user.
1364      *
1365      * @return An {@link AlarmClockInfo} object describing the next upcoming alarm
1366      *   clock event that will occur within the given user.  If there are no alarm clock
1367      *   events currently scheduled in that user, this method will return {@code null}.
1368      *
1369      * @see #setAlarmClock
1370      * @see AlarmClockInfo
1371      * @see #ACTION_NEXT_ALARM_CLOCK_CHANGED
1372      *
1373      * @hide
1374      */
getNextAlarmClock(int userId)1375     public AlarmClockInfo getNextAlarmClock(int userId) {
1376         try {
1377             return mService.getNextAlarmClock(userId);
1378         } catch (RemoteException ex) {
1379             throw ex.rethrowFromSystemServer();
1380         }
1381     }
1382 
1383     /**
1384      * An immutable description of a scheduled "alarm clock" event.
1385      *
1386      * @see AlarmManager#setAlarmClock
1387      * @see AlarmManager#getNextAlarmClock
1388      */
1389     public static final class AlarmClockInfo implements Parcelable {
1390 
1391         private final long mTriggerTime;
1392         private final PendingIntent mShowIntent;
1393 
1394         /**
1395          * Creates a new alarm clock description.
1396          *
1397          * @param triggerTime time at which the underlying alarm is triggered in wall time
1398          *                    milliseconds since the epoch
1399          * @param showIntent an intent that can be used to show or edit details of
1400          *                        the alarm clock.
1401          */
AlarmClockInfo(long triggerTime, PendingIntent showIntent)1402         public AlarmClockInfo(long triggerTime, PendingIntent showIntent) {
1403             mTriggerTime = triggerTime;
1404             mShowIntent = showIntent;
1405         }
1406 
1407         /**
1408          * Use the {@link #CREATOR}
1409          * @hide
1410          */
AlarmClockInfo(Parcel in)1411         AlarmClockInfo(Parcel in) {
1412             mTriggerTime = in.readLong();
1413             mShowIntent = in.readParcelable(PendingIntent.class.getClassLoader());
1414         }
1415 
1416         /**
1417          * Returns the time at which the alarm is going to trigger.
1418          *
1419          * This value is UTC wall clock time in milliseconds, as returned by
1420          * {@link System#currentTimeMillis()} for example.
1421          */
getTriggerTime()1422         public long getTriggerTime() {
1423             return mTriggerTime;
1424         }
1425 
1426         /**
1427          * Returns an intent that can be used to show or edit details of the alarm clock in
1428          * the application that scheduled it.
1429          *
1430          * <p class="note">Beware that any application can retrieve and send this intent,
1431          * potentially with additional fields filled in. See
1432          * {@link PendingIntent#send(android.content.Context, int, android.content.Intent)
1433          * PendingIntent.send()} and {@link android.content.Intent#fillIn Intent.fillIn()}
1434          * for details.
1435          */
getShowIntent()1436         public PendingIntent getShowIntent() {
1437             return mShowIntent;
1438         }
1439 
1440         @Override
describeContents()1441         public int describeContents() {
1442             return 0;
1443         }
1444 
1445         @Override
writeToParcel(Parcel dest, int flags)1446         public void writeToParcel(Parcel dest, int flags) {
1447             dest.writeLong(mTriggerTime);
1448             dest.writeParcelable(mShowIntent, flags);
1449         }
1450 
1451         public static final @android.annotation.NonNull Creator<AlarmClockInfo> CREATOR = new Creator<AlarmClockInfo>() {
1452             @Override
1453             public AlarmClockInfo createFromParcel(Parcel in) {
1454                 return new AlarmClockInfo(in);
1455             }
1456 
1457             @Override
1458             public AlarmClockInfo[] newArray(int size) {
1459                 return new AlarmClockInfo[size];
1460             }
1461         };
1462 
1463         /** @hide */
dumpDebug(ProtoOutputStream proto, long fieldId)1464         public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1465             final long token = proto.start(fieldId);
1466             proto.write(AlarmClockInfoProto.TRIGGER_TIME_MS, mTriggerTime);
1467             if (mShowIntent != null) {
1468                 mShowIntent.dumpDebug(proto, AlarmClockInfoProto.SHOW_INTENT);
1469             }
1470             proto.end(token);
1471         }
1472     }
1473 }
1474