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