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