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