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