blob: 3a34b7926611722e8d5697f727cf54bc9f4421ae [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060019import android.annotation.IntDef;
Christopher Tate8d3079f2017-06-05 18:13:52 -070020import android.annotation.RequiresPermission;
Adrian Roosc42a1e12014-07-07 23:35:53 +020021import android.annotation.SdkConstant;
David Christiec20b7952014-09-04 11:29:01 -070022import android.annotation.SystemApi;
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060023import android.annotation.SystemService;
Mathew Inwood61e8ae62018-08-14 14:17:44 +010024import android.annotation.UnsupportedAppUsage;
Christopher Tatee0a22b32013-07-11 14:43:13 -070025import android.content.Context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.Intent;
Christopher Tatee0a22b32013-07-11 14:43:13 -070027import android.os.Build;
Christopher Tate14a7bb02015-10-01 10:24:31 -070028import android.os.Handler;
Jose Lima235510e2014-08-13 12:50:01 -070029import android.os.Parcel;
30import android.os.Parcelable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.RemoteException;
David Christieebe51fc2013-07-26 13:23:29 -070032import android.os.WorkSource;
Narayan Kamatha78240b2015-04-24 13:22:03 +010033import android.text.TextUtils;
Christopher Tate09d7d8f2016-05-31 15:08:04 -070034import android.util.ArrayMap;
Christopher Tate14a7bb02015-10-01 10:24:31 -070035import android.util.Log;
Kweku Adams61e03292017-10-19 14:27:12 -070036import android.util.proto.ProtoOutputStream;
Christopher Tate14a7bb02015-10-01 10:24:31 -070037
Neil Fullerb8383a12018-11-16 21:46:33 +000038import libcore.timezone.ZoneInfoDB;
Narayan Kamatha78240b2015-04-24 13:22:03 +010039
40import java.io.IOException;
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060041import java.lang.annotation.Retention;
42import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
44/**
45 * This class provides access to the system alarm services. These allow you
46 * to schedule your application to be run at some point in the future. When
47 * an alarm goes off, the {@link Intent} that had been registered for it
48 * is broadcast by the system, automatically starting the target application
49 * if it is not already running. Registered alarms are retained while the
50 * device is asleep (and can optionally wake the device up if they go off
51 * during that time), but will be cleared if it is turned off and rebooted.
Kweku Adams61e03292017-10-19 14:27:12 -070052 *
Chris Tatea34df8a22009-04-02 23:15:58 -070053 * <p>The Alarm Manager holds a CPU wake lock as long as the alarm receiver's
54 * onReceive() method is executing. This guarantees that the phone will not sleep
55 * until you have finished handling the broadcast. Once onReceive() returns, the
56 * Alarm Manager releases this wake lock. This means that the phone will in some
57 * cases sleep as soon as your onReceive() method completes. If your alarm receiver
58 * called {@link android.content.Context#startService Context.startService()}, it
59 * is possible that the phone will sleep before the requested service is launched.
60 * To prevent this, your BroadcastReceiver and Service will need to implement a
61 * separate wake lock policy to ensure that the phone continues running until the
62 * service becomes available.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 *
64 * <p><b>Note: The Alarm Manager is intended for cases where you want to have
65 * your application code run at a specific time, even if your application is
66 * not currently running. For normal timing operations (ticks, timeouts,
67 * etc) it is easier and much more efficient to use
68 * {@link android.os.Handler}.</b>
69 *
Christopher Tate109e4db2013-10-25 16:14:38 -070070 * <p class="caution"><strong>Note:</strong> Beginning with API 19
71 * ({@link android.os.Build.VERSION_CODES#KITKAT}) alarm delivery is inexact:
72 * the OS will shift alarms in order to minimize wakeups and battery use. There are
73 * new APIs to support applications which need strict delivery guarantees; see
74 * {@link #setWindow(int, long, long, PendingIntent)} and
75 * {@link #setExact(int, long, PendingIntent)}. Applications whose {@code targetSdkVersion}
76 * is earlier than API 19 will continue to see the previous behavior in which all
77 * alarms are delivered exactly when requested.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 */
Jeff Sharkeyd86b8fe2017-06-02 17:36:26 -060079@SystemService(Context.ALARM_SERVICE)
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -070080public class AlarmManager {
Christopher Tate14a7bb02015-10-01 10:24:31 -070081 private static final String TAG = "AlarmManager";
82
Jeff Sharkey30e06bb2017-04-24 11:18:03 -060083 /** @hide */
84 @IntDef(prefix = { "RTC", "ELAPSED" }, value = {
85 RTC_WAKEUP,
86 RTC,
87 ELAPSED_REALTIME_WAKEUP,
88 ELAPSED_REALTIME,
89 })
90 @Retention(RetentionPolicy.SOURCE)
91 public @interface AlarmType {}
92
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 /**
94 * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
95 * (wall clock time in UTC), which will wake up the device when
96 * it goes off.
97 */
98 public static final int RTC_WAKEUP = 0;
99 /**
100 * Alarm time in {@link System#currentTimeMillis System.currentTimeMillis()}
101 * (wall clock time in UTC). This alarm does not wake the
102 * device up; if it goes off while the device is asleep, it will not be
103 * delivered until the next time the device wakes up.
104 */
105 public static final int RTC = 1;
106 /**
107 * Alarm time in {@link android.os.SystemClock#elapsedRealtime
108 * SystemClock.elapsedRealtime()} (time since boot, including sleep),
109 * which will wake up the device when it goes off.
110 */
111 public static final int ELAPSED_REALTIME_WAKEUP = 2;
112 /**
113 * Alarm time in {@link android.os.SystemClock#elapsedRealtime
114 * SystemClock.elapsedRealtime()} (time since boot, including sleep).
115 * This alarm does not wake the device up; if it goes off while the device
116 * is asleep, it will not be delivered until the next time the device
117 * wakes up.
118 */
119 public static final int ELAPSED_REALTIME = 3;
120
Adrian Roosc42a1e12014-07-07 23:35:53 +0200121 /**
122 * Broadcast Action: Sent after the value returned by
123 * {@link #getNextAlarmClock()} has changed.
124 *
125 * <p class="note">This is a protected intent that can only be sent by the system.
126 * It is only sent to registered receivers.</p>
127 */
128 @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
129 public static final String ACTION_NEXT_ALARM_CLOCK_CHANGED =
130 "android.app.action.NEXT_ALARM_CLOCK_CHANGED";
131
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700132 /** @hide */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100133 @UnsupportedAppUsage
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700134 public static final long WINDOW_EXACT = 0;
135 /** @hide */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100136 @UnsupportedAppUsage
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700137 public static final long WINDOW_HEURISTIC = -1;
138
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700139 /**
140 * Flag for alarms: this is to be a stand-alone alarm, that should not be batched with
141 * other alarms.
142 * @hide
143 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100144 @UnsupportedAppUsage
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700145 public static final int FLAG_STANDALONE = 1<<0;
146
147 /**
148 * Flag for alarms: this alarm would like to wake the device even if it is idle. This
149 * is, for example, an alarm for an alarm clock.
150 * @hide
151 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100152 @UnsupportedAppUsage
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700153 public static final int FLAG_WAKE_FROM_IDLE = 1<<1;
154
155 /**
156 * Flag for alarms: this alarm would like to still execute even if the device is
157 * idle. This won't bring the device out of idle, just allow this specific alarm to
158 * run. Note that this means the actual time this alarm goes off can be inconsistent
159 * with the time of non-allow-while-idle alarms (it could go earlier than the time
160 * requested by another alarm).
161 *
162 * @hide
163 */
164 public static final int FLAG_ALLOW_WHILE_IDLE = 1<<2;
165
166 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700167 * Flag for alarms: same as {@link #FLAG_ALLOW_WHILE_IDLE}, but doesn't have restrictions
168 * on how frequently it can be scheduled. Only available (and automatically applied) to
169 * system alarms.
170 *
171 * @hide
172 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100173 @UnsupportedAppUsage
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700174 public static final int FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED = 1<<3;
175
176 /**
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700177 * Flag for alarms: this alarm marks the point where we would like to come out of idle
178 * mode. It may be moved by the alarm manager to match the first wake-from-idle alarm.
179 * Scheduling an alarm with this flag puts the alarm manager in to idle mode, where it
180 * avoids scheduling any further alarms until the marker alarm is executed.
181 * @hide
182 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100183 @UnsupportedAppUsage
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700184 public static final int FLAG_IDLE_UNTIL = 1<<4;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700185
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100186 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 private final IAlarmManager mService;
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700188 private final Context mContext;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700189 private final String mPackageName;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700190 private final boolean mAlwaysExact;
Narayan Kamatha78240b2015-04-24 13:22:03 +0100191 private final int mTargetSdkVersion;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700192 private final Handler mMainThreadHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Christopher Tate14a7bb02015-10-01 10:24:31 -0700194 /**
195 * Direct-notification alarms: the requester must be running continuously from the
196 * time the alarm is set to the time it is delivered, or delivery will fail. Only
197 * one-shot alarms can be set using this mechanism, not repeating alarms.
198 */
199 public interface OnAlarmListener {
200 /**
201 * Callback method that is invoked by the system when the alarm time is reached.
202 */
203 public void onAlarm();
204 }
205
206 final class ListenerWrapper extends IAlarmListener.Stub implements Runnable {
207 final OnAlarmListener mListener;
208 Handler mHandler;
209 IAlarmCompleteListener mCompletion;
210
211 public ListenerWrapper(OnAlarmListener listener) {
212 mListener = listener;
213 }
214
215 public void setHandler(Handler h) {
216 mHandler = h;
217 }
218
219 public void cancel() {
220 try {
221 mService.remove(null, this);
222 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700223 throw ex.rethrowFromSystemServer();
Christopher Tate14a7bb02015-10-01 10:24:31 -0700224 }
225
226 synchronized (AlarmManager.class) {
227 if (sWrappers != null) {
228 sWrappers.remove(mListener);
229 }
230 }
231 }
232
233 @Override
234 public void doAlarm(IAlarmCompleteListener alarmManager) {
235 mCompletion = alarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700236
Christopher Tate14a7bb02015-10-01 10:24:31 -0700237 // Remove this listener from the wrapper cache first; the server side
238 // already considers it gone
239 synchronized (AlarmManager.class) {
240 if (sWrappers != null) {
241 sWrappers.remove(mListener);
242 }
243 }
244
Makoto Onukia7d39cf2017-05-04 08:38:07 -0700245 mHandler.post(this);
246 }
247
248 @Override
249 public void run() {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700250 // Now deliver it to the app
251 try {
252 mListener.onAlarm();
253 } finally {
254 // No catch -- make sure to report completion to the system process,
255 // but continue to allow the exception to crash the app.
256
257 try {
258 mCompletion.alarmComplete(this);
259 } catch (Exception e) {
260 Log.e(TAG, "Unable to report completion to Alarm Manager!", e);
261 }
262 }
263 }
264 }
265
266 // Tracking of the OnAlarmListener -> wrapper mapping, for cancel() support.
267 // Access is synchronized on the AlarmManager class object.
Christopher Tate09d7d8f2016-05-31 15:08:04 -0700268 private static ArrayMap<OnAlarmListener, ListenerWrapper> sWrappers;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 /**
271 * package private on purpose
272 */
Christopher Tatee0a22b32013-07-11 14:43:13 -0700273 AlarmManager(IAlarmManager service, Context ctx) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274 mService = service;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700275
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700276 mContext = ctx;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700277 mPackageName = ctx.getPackageName();
Narayan Kamatha78240b2015-04-24 13:22:03 +0100278 mTargetSdkVersion = ctx.getApplicationInfo().targetSdkVersion;
279 mAlwaysExact = (mTargetSdkVersion < Build.VERSION_CODES.KITKAT);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700280 mMainThreadHandler = new Handler(ctx.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 }
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700282
283 private long legacyExactLength() {
284 return (mAlwaysExact ? WINDOW_EXACT : WINDOW_HEURISTIC);
285 }
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 /**
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700288 * <p>Schedule an alarm. <b>Note: for timing operations (ticks, timeouts,
Christopher Tate062bce72013-10-25 13:59:44 -0700289 * etc) it is easier and much more efficient to use {@link android.os.Handler}.</b>
290 * If there is already an alarm scheduled for the same IntentSender, that previous
291 * alarm will first be canceled.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 *
Christopher Tate062bce72013-10-25 13:59:44 -0700293 * <p>If the stated trigger time is in the past, the alarm will be triggered
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 * immediately. If there is already an alarm for this Intent
295 * scheduled (with the equality of two intents being defined by
296 * {@link Intent#filterEquals}), then it will be removed and replaced by
297 * this one.
298 *
299 * <p>
Christopher Tate062bce72013-10-25 13:59:44 -0700300 * The alarm is an Intent broadcast that goes to a broadcast receiver that
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 * you registered with {@link android.content.Context#registerReceiver}
302 * or through the &lt;receiver&gt; tag in an AndroidManifest.xml file.
303 *
304 * <p>
305 * Alarm intents are delivered with a data extra of type int called
306 * {@link Intent#EXTRA_ALARM_COUNT Intent.EXTRA_ALARM_COUNT} that indicates
307 * how many past alarm events have been accumulated into this intent
308 * broadcast. Recurring alarms that have gone undelivered because the
Kweku Adams61e03292017-10-19 14:27:12 -0700309 * phone was asleep may have a count greater than one when delivered.
Christopher Tate062bce72013-10-25 13:59:44 -0700310 *
Christopher Tate109e4db2013-10-25 16:14:38 -0700311 * <div class="note">
Christopher Tate062bce72013-10-25 13:59:44 -0700312 * <p>
313 * <b>Note:</b> Beginning in API 19, the trigger time passed to this method
314 * is treated as inexact: the alarm will not be delivered before this time, but
315 * may be deferred and delivered some time later. The OS will use
316 * this policy in order to "batch" alarms together across the entire system,
317 * minimizing the number of times the device needs to "wake up" and minimizing
318 * battery use. In general, alarms scheduled in the near future will not
319 * be deferred as long as alarms scheduled far in the future.
320 *
321 * <p>
322 * With the new batching policy, delivery ordering guarantees are not as
323 * strong as they were previously. If the application sets multiple alarms,
Christopher Tate109e4db2013-10-25 16:14:38 -0700324 * it is possible that these alarms' <em>actual</em> delivery ordering may not match
325 * the order of their <em>requested</em> delivery times. If your application has
Christopher Tate062bce72013-10-25 13:59:44 -0700326 * strong ordering requirements there are other APIs that you can use to get
327 * the necessary behavior; see {@link #setWindow(int, long, long, PendingIntent)}
328 * and {@link #setExact(int, long, PendingIntent)}.
329 *
330 * <p>
Christopher Tate109e4db2013-10-25 16:14:38 -0700331 * Applications whose {@code targetSdkVersion} is before API 19 will
Christopher Tate062bce72013-10-25 13:59:44 -0700332 * continue to get the previous alarm behavior: all of their scheduled alarms
333 * will be treated as exact.
Christopher Tate109e4db2013-10-25 16:14:38 -0700334 * </div>
Christopher Tate062bce72013-10-25 13:59:44 -0700335 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600336 * @param type type of alarm.
Jesse Wilson79074cd2011-12-22 22:51:37 -0500337 * @param triggerAtMillis time in milliseconds that the alarm should go
338 * off, using the appropriate clock (depending on the alarm type).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 * @param operation Action to perform when the alarm goes off;
340 * typically comes from {@link PendingIntent#getBroadcast
341 * IntentSender.getBroadcast()}.
342 *
343 * @see android.os.Handler
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700344 * @see #setExact
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 * @see #setRepeating
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700346 * @see #setWindow
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 * @see #cancel
348 * @see android.content.Context#sendBroadcast
349 * @see android.content.Context#registerReceiver
350 * @see android.content.Intent#filterEquals
351 * @see #ELAPSED_REALTIME
352 * @see #ELAPSED_REALTIME_WAKEUP
353 * @see #RTC
354 * @see #RTC_WAKEUP
355 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600356 public void set(@AlarmType int type, long triggerAtMillis, PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700357 setImpl(type, triggerAtMillis, legacyExactLength(), 0, 0, operation, null, null,
358 null, null, null);
359 }
360
361 /**
362 * Direct callback version of {@link #set(int, long, PendingIntent)}. Rather than
363 * supplying a PendingIntent to be sent when the alarm time is reached, this variant
364 * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
365 * <p>
366 * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
367 * invoked via the specified target Handler, or on the application's main looper
368 * if {@code null} is passed as the {@code targetHandler} parameter.
369 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600370 * @param type type of alarm.
Christopher Tate14a7bb02015-10-01 10:24:31 -0700371 * @param triggerAtMillis time in milliseconds that the alarm should go
372 * off, using the appropriate clock (depending on the alarm type).
373 * @param tag string describing the alarm, used for logging and battery-use
374 * attribution
375 * @param listener {@link OnAlarmListener} instance whose
376 * {@link OnAlarmListener#onAlarm() onAlarm()} method will be
377 * called when the alarm time is reached. A given OnAlarmListener instance can
378 * only be the target of a single pending alarm, just as a given PendingIntent
379 * can only be used with one alarm at a time.
380 * @param targetHandler {@link Handler} on which to execute the listener's onAlarm()
381 * callback, or {@code null} to run that callback on the main looper.
382 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600383 public void set(@AlarmType int type, long triggerAtMillis, String tag, OnAlarmListener listener,
Christopher Tate14a7bb02015-10-01 10:24:31 -0700384 Handler targetHandler) {
385 setImpl(type, triggerAtMillis, legacyExactLength(), 0, 0, null, listener, tag,
386 targetHandler, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
388
389 /**
390 * Schedule a repeating alarm. <b>Note: for timing operations (ticks,
391 * timeouts, etc) it is easier and much more efficient to use
392 * {@link android.os.Handler}.</b> If there is already an alarm scheduled
393 * for the same IntentSender, it will first be canceled.
394 *
Christopher Tate062bce72013-10-25 13:59:44 -0700395 * <p>Like {@link #set}, except you can also supply a period at which
396 * the alarm will automatically repeat. This alarm continues
397 * repeating until explicitly removed with {@link #cancel}. If the stated
398 * trigger time is in the past, the alarm will be triggered immediately, with an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 * alarm count depending on how far in the past the trigger time is relative
400 * to the repeat interval.
401 *
402 * <p>If an alarm is delayed (by system sleep, for example, for non
403 * _WAKEUP alarm types), a skipped repeat will be delivered as soon as
404 * possible. After that, future alarms will be delivered according to the
405 * original schedule; they do not drift over time. For example, if you have
406 * set a recurring alarm for the top of every hour but the phone was asleep
407 * from 7:45 until 8:45, an alarm will be sent as soon as the phone awakens,
408 * then the next alarm will be sent at 9:00.
Kweku Adams61e03292017-10-19 14:27:12 -0700409 *
410 * <p>If your application wants to allow the delivery times to drift in
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 * order to guarantee that at least a certain time interval always elapses
Kweku Adams61e03292017-10-19 14:27:12 -0700412 * between alarms, then the approach to take is to use one-time alarms,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 * scheduling the next one yourself when handling each alarm delivery.
414 *
Christopher Tate109e4db2013-10-25 16:14:38 -0700415 * <p class="note">
Christopher Tate062bce72013-10-25 13:59:44 -0700416 * <b>Note:</b> as of API 19, all repeating alarms are inexact. If your
417 * application needs precise delivery times then it must use one-time
418 * exact alarms, rescheduling each time as described above. Legacy applications
Christopher Tate109e4db2013-10-25 16:14:38 -0700419 * whose {@code targetSdkVersion} is earlier than API 19 will continue to have all
Christopher Tate062bce72013-10-25 13:59:44 -0700420 * of their alarms, including repeating alarms, treated as exact.
421 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600422 * @param type type of alarm.
Jesse Wilson79074cd2011-12-22 22:51:37 -0500423 * @param triggerAtMillis time in milliseconds that the alarm should first
424 * go off, using the appropriate clock (depending on the alarm type).
425 * @param intervalMillis interval in milliseconds between subsequent repeats
426 * of the alarm.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 * @param operation Action to perform when the alarm goes off;
428 * typically comes from {@link PendingIntent#getBroadcast
429 * IntentSender.getBroadcast()}.
430 *
431 * @see android.os.Handler
432 * @see #set
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700433 * @see #setExact
434 * @see #setWindow
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 * @see #cancel
436 * @see android.content.Context#sendBroadcast
437 * @see android.content.Context#registerReceiver
438 * @see android.content.Intent#filterEquals
439 * @see #ELAPSED_REALTIME
440 * @see #ELAPSED_REALTIME_WAKEUP
441 * @see #RTC
442 * @see #RTC_WAKEUP
443 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600444 public void setRepeating(@AlarmType int type, long triggerAtMillis,
Jesse Wilson79074cd2011-12-22 22:51:37 -0500445 long intervalMillis, PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700446 setImpl(type, triggerAtMillis, legacyExactLength(), intervalMillis, 0, operation,
447 null, null, null, null, null);
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700448 }
449
450 /**
Christopher Tate062bce72013-10-25 13:59:44 -0700451 * Schedule an alarm to be delivered within a given window of time. This method
452 * is similar to {@link #set(int, long, PendingIntent)}, but allows the
453 * application to precisely control the degree to which its delivery might be
454 * adjusted by the OS. This method allows an application to take advantage of the
455 * battery optimizations that arise from delivery batching even when it has
456 * modest timeliness requirements for its alarms.
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700457 *
Christopher Tate062bce72013-10-25 13:59:44 -0700458 * <p>
Christopher Tate109e4db2013-10-25 16:14:38 -0700459 * This method can also be used to achieve strict ordering guarantees among
460 * multiple alarms by ensuring that the windows requested for each alarm do
461 * not intersect.
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700462 *
Christopher Tate062bce72013-10-25 13:59:44 -0700463 * <p>
464 * When precise delivery is not required, applications should use the standard
465 * {@link #set(int, long, PendingIntent)} method. This will give the OS the most
Christopher Tate109e4db2013-10-25 16:14:38 -0700466 * flexibility to minimize wakeups and battery use. For alarms that must be delivered
Christopher Tate062bce72013-10-25 13:59:44 -0700467 * at precisely-specified times with no acceptable variation, applications can use
468 * {@link #setExact(int, long, PendingIntent)}.
469 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600470 * @param type type of alarm.
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700471 * @param windowStartMillis The earliest time, in milliseconds, that the alarm should
472 * be delivered, expressed in the appropriate clock's units (depending on the alarm
473 * type).
474 * @param windowLengthMillis The length of the requested delivery window,
475 * in milliseconds. The alarm will be delivered no later than this many
Christopher Tate062bce72013-10-25 13:59:44 -0700476 * milliseconds after {@code windowStartMillis}. Note that this parameter
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700477 * is a <i>duration,</i> not the timestamp of the end of the window.
478 * @param operation Action to perform when the alarm goes off;
479 * typically comes from {@link PendingIntent#getBroadcast
480 * IntentSender.getBroadcast()}.
481 *
482 * @see #set
483 * @see #setExact
484 * @see #setRepeating
485 * @see #cancel
486 * @see android.content.Context#sendBroadcast
487 * @see android.content.Context#registerReceiver
488 * @see android.content.Intent#filterEquals
489 * @see #ELAPSED_REALTIME
490 * @see #ELAPSED_REALTIME_WAKEUP
491 * @see #RTC
492 * @see #RTC_WAKEUP
493 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600494 public void setWindow(@AlarmType int type, long windowStartMillis, long windowLengthMillis,
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700495 PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700496 setImpl(type, windowStartMillis, windowLengthMillis, 0, 0, operation,
497 null, null, null, null, null);
498 }
499
500 /**
501 * Direct callback version of {@link #setWindow(int, long, long, PendingIntent)}. Rather
502 * than supplying a PendingIntent to be sent when the alarm time is reached, this variant
503 * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
504 * <p>
505 * The OnAlarmListener {@link OnAlarmListener#onAlarm() onAlarm()} method will be
506 * invoked via the specified target Handler, or on the application's main looper
507 * if {@code null} is passed as the {@code targetHandler} parameter.
508 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600509 public void setWindow(@AlarmType int type, long windowStartMillis, long windowLengthMillis,
Christopher Tate14a7bb02015-10-01 10:24:31 -0700510 String tag, OnAlarmListener listener, Handler targetHandler) {
511 setImpl(type, windowStartMillis, windowLengthMillis, 0, 0, null, listener, tag,
512 targetHandler, null, null);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513 }
514
515 /**
Christopher Tate062bce72013-10-25 13:59:44 -0700516 * Schedule an alarm to be delivered precisely at the stated time.
517 *
518 * <p>
519 * This method is like {@link #set(int, long, PendingIntent)}, but does not permit
520 * the OS to adjust the delivery time. The alarm will be delivered as nearly as
521 * possible to the requested trigger time.
522 *
523 * <p>
524 * <b>Note:</b> only alarms for which there is a strong demand for exact-time
525 * delivery (such as an alarm clock ringing at the requested time) should be
526 * scheduled as exact. Applications are strongly discouraged from using exact
527 * alarms unnecessarily as they reduce the OS's ability to minimize battery use.
528 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600529 * @param type type of alarm.
Christopher Tate062bce72013-10-25 13:59:44 -0700530 * @param triggerAtMillis time in milliseconds that the alarm should go
531 * off, using the appropriate clock (depending on the alarm type).
532 * @param operation Action to perform when the alarm goes off;
533 * typically comes from {@link PendingIntent#getBroadcast
534 * IntentSender.getBroadcast()}.
535 *
536 * @see #set
537 * @see #setRepeating
538 * @see #setWindow
539 * @see #cancel
540 * @see android.content.Context#sendBroadcast
541 * @see android.content.Context#registerReceiver
542 * @see android.content.Intent#filterEquals
543 * @see #ELAPSED_REALTIME
544 * @see #ELAPSED_REALTIME_WAKEUP
545 * @see #RTC
546 * @see #RTC_WAKEUP
Christopher Tatee0a22b32013-07-11 14:43:13 -0700547 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600548 public void setExact(@AlarmType int type, long triggerAtMillis, PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700549 setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, operation, null, null, null,
550 null, null);
551 }
552
553 /**
554 * Direct callback version of {@link #setExact(int, long, PendingIntent)}. Rather
555 * than supplying a PendingIntent to be sent when the alarm time is reached, this variant
556 * supplies an {@link OnAlarmListener} instance that will be invoked at that time.
557 * <p>
558 * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
559 * invoked via the specified target Handler, or on the application's main looper
560 * if {@code null} is passed as the {@code targetHandler} parameter.
561 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600562 public void setExact(@AlarmType int type, long triggerAtMillis, String tag,
563 OnAlarmListener listener, Handler targetHandler) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700564 setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, 0, null, listener, tag,
565 targetHandler, null, null);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700566 }
567
568 /**
569 * Schedule an idle-until alarm, which will keep the alarm manager idle until
570 * the given time.
571 * @hide
572 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600573 public void setIdleUntil(@AlarmType int type, long triggerAtMillis, String tag,
574 OnAlarmListener listener, Handler targetHandler) {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -0700575 setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_IDLE_UNTIL, null,
576 listener, tag, targetHandler, null, null);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200577 }
578
579 /**
Dianne Hackborna4eb31d2017-12-04 17:42:16 -0800580 * Schedule an alarm that represents an alarm clock, which will be used to notify the user
581 * when it goes off. The expectation is that when this alarm triggers, the application will
582 * further wake up the device to tell the user about the alarm -- turning on the screen,
583 * playing a sound, vibrating, etc. As such, the system will typically also use the
584 * information supplied here to tell the user about this upcoming alarm if appropriate.
Adrian Roosc42a1e12014-07-07 23:35:53 +0200585 *
Dianne Hackborna4eb31d2017-12-04 17:42:16 -0800586 * <p>Due to the nature of this kind of alarm, similar to {@link #setExactAndAllowWhileIdle},
587 * these alarms will be allowed to trigger even if the system is in a low-power idle
588 * (a.k.a. doze) mode. The system may also do some prep-work when it sees that such an
589 * alarm coming up, to reduce the amount of background work that could happen if this
590 * causes the device to fully wake up -- this is to avoid situations such as a large number
591 * of devices having an alarm set at the same time in the morning, all waking up at that
592 * time and suddenly swamping the network with pending background work. As such, these
593 * types of alarms can be extremely expensive on battery use and should only be used for
594 * their intended purpose.</p>
Adrian Roosc42a1e12014-07-07 23:35:53 +0200595 *
596 * <p>
597 * This method is like {@link #setExact(int, long, PendingIntent)}, but implies
598 * {@link #RTC_WAKEUP}.
599 *
600 * @param info
601 * @param operation Action to perform when the alarm goes off;
602 * typically comes from {@link PendingIntent#getBroadcast
603 * IntentSender.getBroadcast()}.
604 *
605 * @see #set
606 * @see #setRepeating
607 * @see #setWindow
608 * @see #setExact
609 * @see #cancel
610 * @see #getNextAlarmClock()
611 * @see android.content.Context#sendBroadcast
612 * @see android.content.Context#registerReceiver
613 * @see android.content.Intent#filterEquals
614 */
615 public void setAlarmClock(AlarmClockInfo info, PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700616 setImpl(RTC_WAKEUP, info.getTriggerTime(), WINDOW_EXACT, 0, 0, operation,
617 null, null, null, null, info);
David Christieebe51fc2013-07-26 13:23:29 -0700618 }
619
620 /** @hide */
David Christiec20b7952014-09-04 11:29:01 -0700621 @SystemApi
Christopher Tate8d3079f2017-06-05 18:13:52 -0700622 @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600623 public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
624 long intervalMillis, PendingIntent operation, WorkSource workSource) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700625 setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, operation, null, null,
626 null, workSource, null);
627 }
628
629 /**
630 * Direct callback version of {@link #set(int, long, long, long, PendingIntent, WorkSource)}.
631 * Note that repeating alarms must use the PendingIntent variant, not an OnAlarmListener.
632 * <p>
633 * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
634 * invoked via the specified target Handler, or on the application's main looper
635 * if {@code null} is passed as the {@code targetHandler} parameter.
636 *
637 * @hide
638 */
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100639 @UnsupportedAppUsage
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600640 public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
641 long intervalMillis, String tag, OnAlarmListener listener, Handler targetHandler,
642 WorkSource workSource) {
Dianne Hackborne9a988c2016-05-27 17:59:40 -0700643 setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, null, listener, tag,
644 targetHandler, workSource, null);
645 }
646
647 /**
648 * Direct callback version of {@link #set(int, long, long, long, PendingIntent, WorkSource)}.
649 * Note that repeating alarms must use the PendingIntent variant, not an OnAlarmListener.
650 * <p>
651 * The OnAlarmListener's {@link OnAlarmListener#onAlarm() onAlarm()} method will be
652 * invoked via the specified target Handler, or on the application's main looper
653 * if {@code null} is passed as the {@code targetHandler} parameter.
654 *
655 * @hide
656 */
Christopher Tatef2d753e2015-11-04 11:10:48 -0800657 @SystemApi
Christopher Tate8d3079f2017-06-05 18:13:52 -0700658 @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600659 public void set(@AlarmType int type, long triggerAtMillis, long windowMillis,
660 long intervalMillis, OnAlarmListener listener, Handler targetHandler,
661 WorkSource workSource) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700662 setImpl(type, triggerAtMillis, windowMillis, intervalMillis, 0, null, listener, null,
663 targetHandler, workSource, null);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700664 }
665
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600666 private void setImpl(@AlarmType int type, long triggerAtMillis, long windowMillis,
667 long intervalMillis, int flags, PendingIntent operation, final OnAlarmListener listener,
668 String listenerTag, Handler targetHandler, WorkSource workSource,
669 AlarmClockInfo alarmClock) {
Christopher Tate5f221e82013-07-30 17:13:15 -0700670 if (triggerAtMillis < 0) {
Christopher Tate56cfa242013-07-30 19:09:41 -0700671 /* NOTYET
Christopher Tate5f221e82013-07-30 17:13:15 -0700672 if (mAlwaysExact) {
673 // Fatal error for KLP+ apps to use negative trigger times
674 throw new IllegalArgumentException("Invalid alarm trigger time "
675 + triggerAtMillis);
676 }
Christopher Tate56cfa242013-07-30 19:09:41 -0700677 */
Christopher Tate5f221e82013-07-30 17:13:15 -0700678 triggerAtMillis = 0;
679 }
David Christieebe51fc2013-07-26 13:23:29 -0700680
Christopher Tate14a7bb02015-10-01 10:24:31 -0700681 ListenerWrapper recipientWrapper = null;
682 if (listener != null) {
683 synchronized (AlarmManager.class) {
684 if (sWrappers == null) {
Christopher Tate09d7d8f2016-05-31 15:08:04 -0700685 sWrappers = new ArrayMap<OnAlarmListener, ListenerWrapper>();
Christopher Tate14a7bb02015-10-01 10:24:31 -0700686 }
687
Christopher Tated0cca792016-04-21 15:05:34 -0700688 recipientWrapper = sWrappers.get(listener);
689 // no existing wrapper => build a new one
690 if (recipientWrapper == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700691 recipientWrapper = new ListenerWrapper(listener);
Christopher Tated0cca792016-04-21 15:05:34 -0700692 sWrappers.put(listener, recipientWrapper);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700693 }
694 }
695
696 final Handler handler = (targetHandler != null) ? targetHandler : mMainThreadHandler;
697 recipientWrapper.setHandler(handler);
698 }
699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 try {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700701 mService.set(mPackageName, type, triggerAtMillis, windowMillis, intervalMillis, flags,
702 operation, recipientWrapper, listenerTag, workSource, alarmClock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700704 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 }
706 }
707
708 /**
Christopher Tate109e4db2013-10-25 16:14:38 -0700709 * Available inexact recurrence interval recognized by
710 * {@link #setInexactRepeating(int, long, long, PendingIntent)}
711 * when running on Android prior to API 19.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 */
713 public static final long INTERVAL_FIFTEEN_MINUTES = 15 * 60 * 1000;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700714
715 /**
Christopher Tate109e4db2013-10-25 16:14:38 -0700716 * Available inexact recurrence interval recognized by
717 * {@link #setInexactRepeating(int, long, long, PendingIntent)}
718 * when running on Android prior to API 19.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 public static final long INTERVAL_HALF_HOUR = 2*INTERVAL_FIFTEEN_MINUTES;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700721
722 /**
Christopher Tate109e4db2013-10-25 16:14:38 -0700723 * Available inexact recurrence interval recognized by
724 * {@link #setInexactRepeating(int, long, long, PendingIntent)}
725 * when running on Android prior to API 19.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 public static final long INTERVAL_HOUR = 2*INTERVAL_HALF_HOUR;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700728
729 /**
Christopher Tate109e4db2013-10-25 16:14:38 -0700730 * Available inexact recurrence interval recognized by
731 * {@link #setInexactRepeating(int, long, long, PendingIntent)}
732 * when running on Android prior to API 19.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700733 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 public static final long INTERVAL_HALF_DAY = 12*INTERVAL_HOUR;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700735
736 /**
Christopher Tate109e4db2013-10-25 16:14:38 -0700737 * Available inexact recurrence interval recognized by
738 * {@link #setInexactRepeating(int, long, long, PendingIntent)}
739 * when running on Android prior to API 19.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700740 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 public static final long INTERVAL_DAY = 2*INTERVAL_HALF_DAY;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 /**
744 * Schedule a repeating alarm that has inexact trigger time requirements;
745 * for example, an alarm that repeats every hour, but not necessarily at
746 * the top of every hour. These alarms are more power-efficient than
Christopher Tate109e4db2013-10-25 16:14:38 -0700747 * the strict recurrences traditionally supplied by {@link #setRepeating}, since the
748 * system can adjust alarms' delivery times to cause them to fire simultaneously,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 * avoiding waking the device from sleep more than necessary.
Christopher Tate109e4db2013-10-25 16:14:38 -0700750 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 * <p>Your alarm's first trigger will not be before the requested time,
752 * but it might not occur for almost a full interval after that time. In
753 * addition, while the overall period of the repeating alarm will be as
754 * requested, the time between any two successive firings of the alarm
755 * may vary. If your application demands very low jitter, use
Christopher Tate109e4db2013-10-25 16:14:38 -0700756 * one-shot alarms with an appropriate window instead; see {@link
757 * #setWindow(int, long, long, PendingIntent)} and
758 * {@link #setExact(int, long, PendingIntent)}.
759 *
760 * <p class="note">
761 * As of API 19, all repeating alarms are inexact. Because this method has
762 * been available since API 3, your application can safely call it and be
763 * assured that it will get similar behavior on both current and older versions
764 * of Android.
Jesse Wilson79074cd2011-12-22 22:51:37 -0500765 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600766 * @param type type of alarm.
Jesse Wilson79074cd2011-12-22 22:51:37 -0500767 * @param triggerAtMillis time in milliseconds that the alarm should first
768 * go off, using the appropriate clock (depending on the alarm type). This
769 * is inexact: the alarm will not fire before this time, but there may be a
770 * delay of almost an entire alarm interval before the first invocation of
771 * the alarm.
772 * @param intervalMillis interval in milliseconds between subsequent repeats
Christopher Tate109e4db2013-10-25 16:14:38 -0700773 * of the alarm. Prior to API 19, if this is one of INTERVAL_FIFTEEN_MINUTES,
Jesse Wilson79074cd2011-12-22 22:51:37 -0500774 * INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_HALF_DAY, or INTERVAL_DAY
775 * then the alarm will be phase-aligned with other alarms to reduce the
776 * number of wakeups. Otherwise, the alarm will be set as though the
Christopher Tate109e4db2013-10-25 16:14:38 -0700777 * application had called {@link #setRepeating}. As of API 19, all repeating
778 * alarms will be inexact and subject to batching with other alarms regardless
779 * of their stated repeat interval.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 * @param operation Action to perform when the alarm goes off;
781 * typically comes from {@link PendingIntent#getBroadcast
782 * IntentSender.getBroadcast()}.
783 *
784 * @see android.os.Handler
785 * @see #set
786 * @see #cancel
787 * @see android.content.Context#sendBroadcast
788 * @see android.content.Context#registerReceiver
789 * @see android.content.Intent#filterEquals
790 * @see #ELAPSED_REALTIME
791 * @see #ELAPSED_REALTIME_WAKEUP
792 * @see #RTC
793 * @see #RTC_WAKEUP
794 * @see #INTERVAL_FIFTEEN_MINUTES
795 * @see #INTERVAL_HALF_HOUR
796 * @see #INTERVAL_HOUR
797 * @see #INTERVAL_HALF_DAY
798 * @see #INTERVAL_DAY
799 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600800 public void setInexactRepeating(@AlarmType int type, long triggerAtMillis,
Jesse Wilson79074cd2011-12-22 22:51:37 -0500801 long intervalMillis, PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700802 setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, intervalMillis, 0, operation, null,
803 null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700805
806 /**
807 * Like {@link #set(int, long, PendingIntent)}, but this alarm will be allowed to execute
Dianne Hackborna4eb31d2017-12-04 17:42:16 -0800808 * even when the system is in low-power idle (a.k.a. doze) modes. This type of alarm must
809 * <b>only</b> be used for situations where it is actually required that the alarm go off while
810 * in idle -- a reasonable example would be for a calendar notification that should make a
Dianne Hackborn14c5ab42015-07-09 18:17:54 -0700811 * sound so the user is aware of it. When the alarm is dispatched, the app will also be
812 * added to the system's temporary whitelist for approximately 10 seconds to allow that
813 * application to acquire further wake locks in which to complete its work.</p>
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700814 *
Dianne Hackborn14c5ab42015-07-09 18:17:54 -0700815 * <p>These alarms can significantly impact the power use
816 * of the device when idle (and thus cause significant battery blame to the app scheduling
817 * them), so they should be used with care. To reduce abuse, there are restrictions on how
818 * frequently these alarms will go off for a particular application.
819 * Under normal system operation, it will not dispatch these
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700820 * alarms more than about every minute (at which point every such pending alarm is
821 * dispatched); when in low-power idle modes this duration may be significantly longer,
822 * such as 15 minutes.</p>
823 *
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700824 * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
825 * out of order with any other alarms, even those from the same app. This will clearly happen
826 * when the device is idle (since this alarm can go off while idle, when any other alarms
827 * from the app will be held until later), but may also happen even when not idle.</p>
828 *
829 * <p>Regardless of the app's target SDK version, this call always allows batching of the
830 * alarm.</p>
831 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600832 * @param type type of alarm.
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700833 * @param triggerAtMillis time in milliseconds that the alarm should go
834 * off, using the appropriate clock (depending on the alarm type).
835 * @param operation Action to perform when the alarm goes off;
836 * typically comes from {@link PendingIntent#getBroadcast
837 * IntentSender.getBroadcast()}.
838 *
839 * @see #set(int, long, PendingIntent)
840 * @see #setExactAndAllowWhileIdle
841 * @see #cancel
842 * @see android.content.Context#sendBroadcast
843 * @see android.content.Context#registerReceiver
844 * @see android.content.Intent#filterEquals
845 * @see #ELAPSED_REALTIME
846 * @see #ELAPSED_REALTIME_WAKEUP
847 * @see #RTC
848 * @see #RTC_WAKEUP
849 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600850 public void setAndAllowWhileIdle(@AlarmType int type, long triggerAtMillis,
851 PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700852 setImpl(type, triggerAtMillis, WINDOW_HEURISTIC, 0, FLAG_ALLOW_WHILE_IDLE,
853 operation, null, null, null, null, null);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700854 }
855
856 /**
857 * Like {@link #setExact(int, long, PendingIntent)}, but this alarm will be allowed to execute
858 * even when the system is in low-power idle modes. If you don't need exact scheduling of
859 * the alarm but still need to execute while idle, consider using
860 * {@link #setAndAllowWhileIdle}. This type of alarm must <b>only</b>
861 * be used for situations where it is actually required that the alarm go off while in
862 * idle -- a reasonable example would be for a calendar notification that should make a
Dianne Hackborn14c5ab42015-07-09 18:17:54 -0700863 * sound so the user is aware of it. When the alarm is dispatched, the app will also be
864 * added to the system's temporary whitelist for approximately 10 seconds to allow that
865 * application to acquire further wake locks in which to complete its work.</p>
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700866 *
Dianne Hackborn14c5ab42015-07-09 18:17:54 -0700867 * <p>These alarms can significantly impact the power use
868 * of the device when idle (and thus cause significant battery blame to the app scheduling
869 * them), so they should be used with care. To reduce abuse, there are restrictions on how
870 * frequently these alarms will go off for a particular application.
871 * Under normal system operation, it will not dispatch these
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700872 * alarms more than about every minute (at which point every such pending alarm is
873 * dispatched); when in low-power idle modes this duration may be significantly longer,
874 * such as 15 minutes.</p>
875 *
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700876 * <p>Unlike other alarms, the system is free to reschedule this type of alarm to happen
877 * out of order with any other alarms, even those from the same app. This will clearly happen
878 * when the device is idle (since this alarm can go off while idle, when any other alarms
879 * from the app will be held until later), but may also happen even when not idle.
880 * Note that the OS will allow itself more flexibility for scheduling these alarms than
881 * regular exact alarms, since the application has opted into this behavior. When the
882 * device is idle it may take even more liberties with scheduling in order to optimize
883 * for battery life.</p>
884 *
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600885 * @param type type of alarm.
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700886 * @param triggerAtMillis time in milliseconds that the alarm should go
887 * off, using the appropriate clock (depending on the alarm type).
888 * @param operation Action to perform when the alarm goes off;
889 * typically comes from {@link PendingIntent#getBroadcast
890 * IntentSender.getBroadcast()}.
891 *
892 * @see #set
893 * @see #setRepeating
894 * @see #setWindow
895 * @see #cancel
896 * @see android.content.Context#sendBroadcast
897 * @see android.content.Context#registerReceiver
898 * @see android.content.Intent#filterEquals
899 * @see #ELAPSED_REALTIME
900 * @see #ELAPSED_REALTIME_WAKEUP
901 * @see #RTC
902 * @see #RTC_WAKEUP
903 */
Jeff Sharkey30e06bb2017-04-24 11:18:03 -0600904 public void setExactAndAllowWhileIdle(@AlarmType int type, long triggerAtMillis,
905 PendingIntent operation) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700906 setImpl(type, triggerAtMillis, WINDOW_EXACT, 0, FLAG_ALLOW_WHILE_IDLE, operation,
Christopher Tate14a7bb02015-10-01 10:24:31 -0700907 null, null, null, null, null);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700908 }
909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 /**
911 * Remove any alarms with a matching {@link Intent}.
912 * Any alarm, of any type, whose Intent matches this one (as defined by
913 * {@link Intent#filterEquals}), will be canceled.
914 *
915 * @param operation IntentSender which matches a previously added
Christopher Tatebb76a6c2015-12-02 10:54:56 -0800916 * IntentSender. This parameter must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 *
918 * @see #set
919 */
920 public void cancel(PendingIntent operation) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700921 if (operation == null) {
Christopher Tatebb76a6c2015-12-02 10:54:56 -0800922 final String msg = "cancel() called with a null PendingIntent";
923 if (mTargetSdkVersion >= Build.VERSION_CODES.N) {
924 throw new NullPointerException(msg);
925 } else {
926 Log.e(TAG, msg);
927 return;
928 }
Christopher Tate14a7bb02015-10-01 10:24:31 -0700929 }
930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 try {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700932 mService.remove(operation, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700934 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936 }
Dan Egnor97e44942010-02-04 20:27:47 -0800937
938 /**
Christopher Tate14a7bb02015-10-01 10:24:31 -0700939 * Remove any alarm scheduled to be delivered to the given {@link OnAlarmListener}.
940 *
941 * @param listener OnAlarmListener instance that is the target of a currently-set alarm.
942 */
943 public void cancel(OnAlarmListener listener) {
944 if (listener == null) {
Christopher Tatebb76a6c2015-12-02 10:54:56 -0800945 throw new NullPointerException("cancel() called with a null OnAlarmListener");
Christopher Tate14a7bb02015-10-01 10:24:31 -0700946 }
947
948 ListenerWrapper wrapper = null;
949 synchronized (AlarmManager.class) {
Joe LaPenna33ee4bf2016-04-01 13:37:37 -0700950 if (sWrappers != null) {
Christopher Tated0cca792016-04-21 15:05:34 -0700951 wrapper = sWrappers.get(listener);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700952 }
953 }
954
955 if (wrapper == null) {
956 Log.w(TAG, "Unrecognized alarm listener " + listener);
957 return;
958 }
959
960 wrapper.cancel();
961 }
962
963 /**
Dan Egnor97e44942010-02-04 20:27:47 -0800964 * Set the system wall clock time.
965 * Requires the permission android.permission.SET_TIME.
966 *
967 * @param millis time in milliseconds since the Epoch
968 */
Jeff Sharkeyd7d4ecc2018-06-11 14:03:14 -0600969 @RequiresPermission(android.Manifest.permission.SET_TIME)
Dan Egnor97e44942010-02-04 20:27:47 -0800970 public void setTime(long millis) {
971 try {
972 mService.setTime(millis);
973 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -0700974 throw ex.rethrowFromSystemServer();
Dan Egnor97e44942010-02-04 20:27:47 -0800975 }
976 }
977
978 /**
Narayan Kamatha78240b2015-04-24 13:22:03 +0100979 * Sets the system's persistent default time zone. This is the time zone for all apps, even
980 * after a reboot. Use {@link java.util.TimeZone#setDefault} if you just want to change the
981 * time zone within your app, and even then prefer to pass an explicit
982 * {@link java.util.TimeZone} to APIs that require it rather than changing the time zone for
983 * all threads.
Dan Egnor97e44942010-02-04 20:27:47 -0800984 *
Narayan Kamatha78240b2015-04-24 13:22:03 +0100985 * <p> On android M and above, it is an error to pass in a non-Olson timezone to this
986 * function. Note that this is a bad idea on all Android releases because POSIX and
987 * the {@code TimeZone} class have opposite interpretations of {@code '+'} and {@code '-'}
988 * in the same non-Olson ID.
989 *
990 * @param timeZone one of the Olson ids from the list returned by
991 * {@link java.util.TimeZone#getAvailableIDs}
Dan Egnor97e44942010-02-04 20:27:47 -0800992 */
Jeff Sharkeyd7d4ecc2018-06-11 14:03:14 -0600993 @RequiresPermission(android.Manifest.permission.SET_TIME_ZONE)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 public void setTimeZone(String timeZone) {
Narayan Kamatha78240b2015-04-24 13:22:03 +0100995 if (TextUtils.isEmpty(timeZone)) {
996 return;
997 }
998
999 // Reject this timezone if it isn't an Olson zone we recognize.
Dianne Hackborn0e3de6c2015-07-29 15:20:21 -07001000 if (mTargetSdkVersion >= Build.VERSION_CODES.M) {
Narayan Kamatha78240b2015-04-24 13:22:03 +01001001 boolean hasTimeZone = false;
1002 try {
1003 hasTimeZone = ZoneInfoDB.getInstance().hasTimeZone(timeZone);
1004 } catch (IOException ignored) {
1005 }
1006
1007 if (!hasTimeZone) {
1008 throw new IllegalArgumentException("Timezone: " + timeZone + " is not an Olson ID");
1009 }
1010 }
1011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 try {
1013 mService.setTimeZone(timeZone);
1014 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001015 throw ex.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
1017 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02001018
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001019 /** @hide */
1020 public long getNextWakeFromIdleTime() {
1021 try {
1022 return mService.getNextWakeFromIdleTime();
1023 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001024 throw ex.rethrowFromSystemServer();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001025 }
1026 }
1027
Adrian Roosc42a1e12014-07-07 23:35:53 +02001028 /**
1029 * Gets information about the next alarm clock currently scheduled.
1030 *
Christopher Tate2affae92016-03-09 17:42:52 -08001031 * The alarm clocks considered are those scheduled by any application
1032 * using the {@link #setAlarmClock} method.
1033 *
1034 * @return An {@link AlarmClockInfo} object describing the next upcoming alarm
1035 * clock event that will occur. If there are no alarm clock events currently
1036 * scheduled, this method will return {@code null}.
Adrian Roosc42a1e12014-07-07 23:35:53 +02001037 *
1038 * @see #setAlarmClock
1039 * @see AlarmClockInfo
Christopher Tate2affae92016-03-09 17:42:52 -08001040 * @see #ACTION_NEXT_ALARM_CLOCK_CHANGED
Adrian Roosc42a1e12014-07-07 23:35:53 +02001041 */
1042 public AlarmClockInfo getNextAlarmClock() {
Jeff Sharkeyad357d12018-02-02 13:25:31 -07001043 return getNextAlarmClock(mContext.getUserId());
Adrian Roosc42a1e12014-07-07 23:35:53 +02001044 }
1045
1046 /**
1047 * Gets information about the next alarm clock currently scheduled.
1048 *
Christopher Tate2affae92016-03-09 17:42:52 -08001049 * The alarm clocks considered are those scheduled by any application
1050 * using the {@link #setAlarmClock} method within the given user.
1051 *
1052 * @return An {@link AlarmClockInfo} object describing the next upcoming alarm
1053 * clock event that will occur within the given user. If there are no alarm clock
1054 * events currently scheduled in that user, this method will return {@code null}.
Adrian Roosc42a1e12014-07-07 23:35:53 +02001055 *
1056 * @see #setAlarmClock
1057 * @see AlarmClockInfo
Christopher Tate2affae92016-03-09 17:42:52 -08001058 * @see #ACTION_NEXT_ALARM_CLOCK_CHANGED
Adrian Roosc42a1e12014-07-07 23:35:53 +02001059 *
1060 * @hide
1061 */
1062 public AlarmClockInfo getNextAlarmClock(int userId) {
1063 try {
1064 return mService.getNextAlarmClock(userId);
1065 } catch (RemoteException ex) {
Jeff Sharkeyc53962d2016-03-01 19:27:23 -07001066 throw ex.rethrowFromSystemServer();
Adrian Roosc42a1e12014-07-07 23:35:53 +02001067 }
1068 }
Jose Lima235510e2014-08-13 12:50:01 -07001069
1070 /**
Christopher Tate2affae92016-03-09 17:42:52 -08001071 * An immutable description of a scheduled "alarm clock" event.
Jose Lima235510e2014-08-13 12:50:01 -07001072 *
1073 * @see AlarmManager#setAlarmClock
1074 * @see AlarmManager#getNextAlarmClock
1075 */
1076 public static final class AlarmClockInfo implements Parcelable {
1077
1078 private final long mTriggerTime;
1079 private final PendingIntent mShowIntent;
1080
1081 /**
1082 * Creates a new alarm clock description.
1083 *
Kweku Adams61e03292017-10-19 14:27:12 -07001084 * @param triggerTime time at which the underlying alarm is triggered in wall time
Jose Lima235510e2014-08-13 12:50:01 -07001085 * milliseconds since the epoch
1086 * @param showIntent an intent that can be used to show or edit details of
1087 * the alarm clock.
1088 */
1089 public AlarmClockInfo(long triggerTime, PendingIntent showIntent) {
1090 mTriggerTime = triggerTime;
1091 mShowIntent = showIntent;
1092 }
1093
1094 /**
1095 * Use the {@link #CREATOR}
1096 * @hide
1097 */
1098 AlarmClockInfo(Parcel in) {
1099 mTriggerTime = in.readLong();
1100 mShowIntent = in.readParcelable(PendingIntent.class.getClassLoader());
1101 }
1102
1103 /**
1104 * Returns the time at which the alarm is going to trigger.
1105 *
1106 * This value is UTC wall clock time in milliseconds, as returned by
1107 * {@link System#currentTimeMillis()} for example.
1108 */
1109 public long getTriggerTime() {
1110 return mTriggerTime;
1111 }
1112
1113 /**
Shuhrat Dehkanov66729ff2015-05-13 17:16:29 +09001114 * Returns an intent that can be used to show or edit details of the alarm clock in
Jose Lima235510e2014-08-13 12:50:01 -07001115 * the application that scheduled it.
1116 *
Kweku Adams61e03292017-10-19 14:27:12 -07001117 * <p class="note">Beware that any application can retrieve and send this intent,
Jose Lima235510e2014-08-13 12:50:01 -07001118 * potentially with additional fields filled in. See
1119 * {@link PendingIntent#send(android.content.Context, int, android.content.Intent)
1120 * PendingIntent.send()} and {@link android.content.Intent#fillIn Intent.fillIn()}
1121 * for details.
1122 */
1123 public PendingIntent getShowIntent() {
1124 return mShowIntent;
1125 }
1126
1127 @Override
1128 public int describeContents() {
1129 return 0;
1130 }
1131
1132 @Override
1133 public void writeToParcel(Parcel dest, int flags) {
1134 dest.writeLong(mTriggerTime);
1135 dest.writeParcelable(mShowIntent, flags);
1136 }
1137
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -07001138 public static final @android.annotation.NonNull Creator<AlarmClockInfo> CREATOR = new Creator<AlarmClockInfo>() {
Jose Lima235510e2014-08-13 12:50:01 -07001139 @Override
1140 public AlarmClockInfo createFromParcel(Parcel in) {
1141 return new AlarmClockInfo(in);
1142 }
1143
1144 @Override
1145 public AlarmClockInfo[] newArray(int size) {
1146 return new AlarmClockInfo[size];
1147 }
1148 };
Kweku Adams61e03292017-10-19 14:27:12 -07001149
1150 /** @hide */
1151 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1152 final long token = proto.start(fieldId);
1153 proto.write(AlarmClockInfoProto.TRIGGER_TIME_MS, mTriggerTime);
Kweku Adams15afdeb2018-09-04 11:54:46 -07001154 if (mShowIntent != null) {
1155 mShowIntent.writeToProto(proto, AlarmClockInfoProto.SHOW_INTENT);
1156 }
Kweku Adams61e03292017-10-19 14:27:12 -07001157 proto.end(token);
1158 }
Jose Lima235510e2014-08-13 12:50:01 -07001159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160}