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