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