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