aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowAlarmManager.java
blob: 2971b8e57ec283f638ecb324671a66ca4b167892 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
package org.robolectric.shadows;

import static android.app.AlarmManager.RTC_WAKEUP;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.annotation.Nullable;
import android.annotation.RequiresApi;
import android.app.AlarmManager;
import android.app.AlarmManager.AlarmClockInfo;
import android.app.AlarmManager.OnAlarmListener;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.os.WorkSource;
import com.android.internal.annotations.GuardedBy;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;

/** Shadow for {@link android.app.AlarmManager}. */
@Implements(AlarmManager.class)
public class ShadowAlarmManager {

  public static final long WINDOW_EXACT = 0;
  public static final long WINDOW_HEURISTIC = -1;

  private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault();

  private static boolean canScheduleExactAlarms;
  private static boolean autoSchedule;

  private final Handler schedulingHandler = new Handler(Looper.getMainLooper());

  @GuardedBy("scheduledAlarms")
  private final PriorityQueue<InternalScheduledAlarm> scheduledAlarms = new PriorityQueue<>();

  @RealObject private AlarmManager realObject;

  @Resetter
  public static void reset() {
    TimeZone.setDefault(DEFAULT_TIMEZONE);
    canScheduleExactAlarms = false;
    autoSchedule = false;
  }

  /**
   * When set to true, automatically schedules alarms to fire at the appropriate time (with respect
   * to the main Looper time) when they are set. This means that a test as below could be expected
   * to pass:
   *
   * <pre>{@code
   * shadowOf(alarmManager).setAutoSchedule(true);
   * AlarmManager.OnAlarmListener listener = mock(AlarmManager.OnAlarmListener.class);
   * alarmManager.setExact(
   *   ELAPSED_REALTIME_WAKEUP,
   *   SystemClock.elapsedRealtime() + 10,
   *   "tag",
   *   listener,
   *   new Handler(Looper.getMainLooper()));
   * shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(10));
   * verify(listener).onAlarm();
   * }</pre>
   *
   * <p>Alarms are always scheduled with respect to the trigger/window start time - there is no
   * emulation of alarms being reordered, rescheduled, or delayed, as might happen on a real device.
   * If emulating this is necessary, see {@link #fireAlarm(ScheduledAlarm)}.
   *
   * <p>{@link AlarmManager.OnAlarmListener} alarms will be run on the correct Handler/Executor as
   * specified when the alarm is set.
   */
  public static void setAutoSchedule(boolean autoSchedule) {
    ShadowAlarmManager.autoSchedule = autoSchedule;
  }

  @Implementation
  protected void set(int type, long triggerAtMs, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_HEURISTIC, 0L, operation, null, null, false);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void set(
      int type,
      long triggerAtMs,
      @Nullable String tag,
      OnAlarmListener listener,
      @Nullable Handler handler) {
    setImpl(
        type,
        triggerAtMs,
        WINDOW_HEURISTIC,
        0L,
        tag,
        listener,
        new HandlerExecutor(handler),
        null,
        false);
  }

  @Implementation
  protected void setRepeating(
      int type, long triggerAtMs, long intervalMs, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_HEURISTIC, intervalMs, operation, null, null, false);
  }

  @Implementation
  protected void setWindow(
      int type, long windowStartMs, long windowLengthMs, PendingIntent operation) {
    setImpl(type, windowStartMs, windowLengthMs, 0L, operation, null, null, false);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void setWindow(
      int type,
      long windowStartMs,
      long windowLengthMs,
      @Nullable String tag,
      OnAlarmListener listener,
      @Nullable Handler handler) {
    setImpl(
        type,
        windowStartMs,
        windowLengthMs,
        0L,
        tag,
        listener,
        new HandlerExecutor(handler),
        null,
        false);
  }

  @Implementation(minSdk = 34)
  protected void setWindow(
      int type,
      long windowStartMs,
      long windowLengthMs,
      @Nullable String tag,
      Executor executor,
      OnAlarmListener listener) {
    setImpl(type, windowStartMs, windowLengthMs, 0L, tag, listener, executor, null, false);
  }

  @Implementation(minSdk = 34)
  protected void setWindow(
      int type,
      long windowStartMs,
      long windowLengthMs,
      @Nullable String tag,
      Executor executor,
      WorkSource workSource,
      OnAlarmListener listener) {
    setImpl(type, windowStartMs, windowLengthMs, 0L, tag, listener, executor, workSource, false);
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void setPrioritized(
      int type,
      long windowStartMs,
      long windowLengthMs,
      @Nullable String tag,
      Executor executor,
      OnAlarmListener listener) {
    Objects.requireNonNull(executor);
    Objects.requireNonNull(listener);
    setImpl(type, windowStartMs, windowLengthMs, 0L, tag, listener, executor, null, true);
  }

  @Implementation
  protected void setExact(int type, long triggerAtMs, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_EXACT, 0L, operation, null, null, false);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void setExact(
      int type,
      long triggerAtTime,
      @Nullable String tag,
      OnAlarmListener listener,
      @Nullable Handler targetHandler) {
    setImpl(
        type,
        triggerAtTime,
        WINDOW_EXACT,
        0L,
        tag,
        listener,
        new HandlerExecutor(targetHandler),
        null,
        false);
  }

  @RequiresApi(VERSION_CODES.LOLLIPOP)
  @Implementation(minSdk = VERSION_CODES.LOLLIPOP)
  protected void setAlarmClock(AlarmClockInfo info, PendingIntent operation) {
    setImpl(RTC_WAKEUP, info.getTriggerTime(), WINDOW_EXACT, 0L, operation, null, info, true);
  }

  @Implementation
  protected void set(
      int type,
      long triggerAtMs,
      long windowLengthMs,
      long intervalMs,
      PendingIntent operation,
      @Nullable WorkSource workSource) {
    setImpl(type, triggerAtMs, windowLengthMs, intervalMs, operation, workSource, null, false);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void set(
      int type,
      long triggerAtMs,
      long windowLengthMs,
      long intervalMs,
      @Nullable String tag,
      OnAlarmListener listener,
      @Nullable Handler targetHandler,
      @Nullable WorkSource workSource) {
    setImpl(
        type,
        triggerAtMs,
        windowLengthMs,
        intervalMs,
        tag,
        listener,
        new HandlerExecutor(targetHandler),
        workSource,
        false);
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void set(
      int type,
      long triggerAtMs,
      long windowLengthMs,
      long intervalMs,
      OnAlarmListener listener,
      @Nullable Handler targetHandler,
      @Nullable WorkSource workSource) {
    setImpl(
        type,
        triggerAtMs,
        windowLengthMs,
        intervalMs,
        null,
        listener,
        new HandlerExecutor(targetHandler),
        workSource,
        false);
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected void setExact(
      int type,
      long triggerAtMs,
      @Nullable String tag,
      Executor executor,
      WorkSource workSource,
      OnAlarmListener listener) {
    Objects.requireNonNull(workSource);
    setImpl(type, triggerAtMs, WINDOW_EXACT, 0L, tag, listener, executor, workSource, false);
  }

  @Implementation
  protected void setInexactRepeating(
      int type, long triggerAtMs, long intervalMillis, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_HEURISTIC, intervalMillis, operation, null, null, false);
  }

  @Implementation(minSdk = VERSION_CODES.M)
  protected void setAndAllowWhileIdle(int type, long triggerAtMs, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_HEURISTIC, 0L, operation, null, null, true);
  }

  @Implementation(minSdk = VERSION_CODES.M)
  protected void setExactAndAllowWhileIdle(int type, long triggerAtMs, PendingIntent operation) {
    setImpl(type, triggerAtMs, WINDOW_EXACT, 0L, operation, null, null, true);
  }

  @Implementation(minSdk = 34)
  protected void setExactAndAllowWhileIdle(
      int type,
      long triggerAtMs,
      @Nullable String tag,
      Executor executor,
      @Nullable WorkSource workSource,
      OnAlarmListener listener) {
    setImpl(type, triggerAtMs, WINDOW_EXACT, 0L, tag, listener, executor, workSource, true);
  }

  @Implementation
  protected void cancel(PendingIntent operation) {
    synchronized (scheduledAlarms) {
      Iterables.removeIf(
          scheduledAlarms,
          alarm -> {
            if (operation.equals(alarm.operation)) {
              alarm.deschedule();
              return true;
            }
            return false;
          });
    }
  }

  @Implementation(minSdk = VERSION_CODES.N)
  protected void cancel(OnAlarmListener listener) {
    synchronized (scheduledAlarms) {
      Iterables.removeIf(
          scheduledAlarms,
          alarm -> {
            if (listener.equals(alarm.onAlarmListener)) {
              alarm.deschedule();
              return true;
            }
            return false;
          });
    }
  }

  @Implementation(minSdk = 34)
  protected void cancelAll() {
    synchronized (scheduledAlarms) {
      for (InternalScheduledAlarm alarm : scheduledAlarms) {
        alarm.deschedule();
      }
      scheduledAlarms.clear();
    }
  }

  @Implementation
  protected void setTimeZone(String timeZone) {
    // Do the real check first
    reflector(AlarmManagerReflector.class, realObject).setTimeZone(timeZone);
    // Then do the right side effect
    TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
  }

  @Implementation(minSdk = VERSION_CODES.S)
  protected boolean canScheduleExactAlarms() {
    return canScheduleExactAlarms;
  }

  @RequiresApi(VERSION_CODES.LOLLIPOP)
  @Implementation(minSdk = VERSION_CODES.LOLLIPOP)
  @Nullable
  protected AlarmClockInfo getNextAlarmClock() {
    synchronized (scheduledAlarms) {
      for (ScheduledAlarm scheduledAlarm : scheduledAlarms) {
        AlarmClockInfo alarmClockInfo = scheduledAlarm.getAlarmClockInfo();
        if (alarmClockInfo != null) {
          return alarmClockInfo;
        }
      }
      return null;
    }
  }

  private void setImpl(
      int type,
      long triggerAtMs,
      long windowLengthMs,
      long intervalMs,
      PendingIntent operation,
      @Nullable WorkSource workSource,
      @Nullable Object alarmClockInfo,
      boolean allowWhileIdle) {
    synchronized (scheduledAlarms) {
      cancel(operation);
      scheduledAlarms.add(
          new InternalScheduledAlarm(
                  type,
                  triggerAtMs,
                  windowLengthMs,
                  intervalMs,
                  operation,
                  workSource,
                  alarmClockInfo,
                  allowWhileIdle)
              .schedule());
    }
  }

  private void setImpl(
      int type,
      long triggerAtMs,
      long windowLengthMs,
      long intervalMs,
      @Nullable String tag,
      OnAlarmListener listener,
      Executor executor,
      @Nullable WorkSource workSource,
      boolean allowWhileIdle) {
    synchronized (scheduledAlarms) {
      cancel(listener);
      scheduledAlarms.add(
          new InternalScheduledAlarm(
                  type,
                  triggerAtMs,
                  windowLengthMs,
                  intervalMs,
                  tag,
                  listener,
                  executor,
                  workSource,
                  null,
                  allowWhileIdle)
              .schedule());
    }
  }

  /**
   * Returns the earliest scheduled alarm and removes it from the list of scheduled alarms.
   *
   * @deprecated Prefer to use {@link ShadowAlarmManager#setAutoSchedule(boolean)} in combination
   *     with incrementing time to actually run alarms and test their side-effects.
   */
  @Deprecated
  @Nullable
  public ScheduledAlarm getNextScheduledAlarm() {
    synchronized (scheduledAlarms) {
      InternalScheduledAlarm alarm = scheduledAlarms.poll();
      if (alarm != null) {
        alarm.deschedule();
      }
      return alarm;
    }
  }

  /** Returns the earliest scheduled alarm. */
  @Nullable
  public ScheduledAlarm peekNextScheduledAlarm() {
    synchronized (scheduledAlarms) {
      return scheduledAlarms.peek();
    }
  }

  /** Returns a list of all scheduled alarms, ordered from earliest time to latest time. */
  public List<ScheduledAlarm> getScheduledAlarms() {
    synchronized (scheduledAlarms) {
      return new ArrayList<>(scheduledAlarms);
    }
  }

  /**
   * Immediately removes the given alarm from the list of scheduled alarms (and then reschedules it
   * in the case of a repeating alarm) and fires it. The given alarm must on the list of scheduled
   * alarms prior to being fired.
   *
   * <p>Generally prefer to use {@link ShadowAlarmManager#setAutoSchedule(boolean)} in combination
   * with advancing time on the main Looper in order to test alarms - however this method can be
   * useful to emulate rescheduled, reordered, or delayed alarms, as may happen on a real device.
   */
  public void fireAlarm(ScheduledAlarm alarm) {
    synchronized (scheduledAlarms) {
      if (!scheduledAlarms.contains(alarm)) {
        throw new IllegalArgumentException();
      }

      ((InternalScheduledAlarm) alarm).deschedule();
      ((InternalScheduledAlarm) alarm).run();
    }
  }

  /**
   * Sets the schedule exact alarm state reported by {@link AlarmManager#canScheduleExactAlarms()},
   * but has no effect otherwise.
   */
  public static void setCanScheduleExactAlarms(boolean scheduleExactAlarms) {
    canScheduleExactAlarms = scheduleExactAlarms;
  }

  /** Represents a set alarm. */
  public static class ScheduledAlarm implements Comparable<ScheduledAlarm> {

    @Deprecated public final int type;
    @Deprecated public final long triggerAtTime;
    private final long windowLengthMs;
    @Deprecated public final long interval;
    @Nullable private final String tag;
    @Deprecated @Nullable public final PendingIntent operation;
    @Deprecated @Nullable public final OnAlarmListener onAlarmListener;
    @Deprecated @Nullable public final Executor executor;
    @Nullable private final WorkSource workSource;
    @Nullable private final Object alarmClockInfo;
    @Deprecated public final boolean allowWhileIdle;

    @Deprecated @Nullable public final PendingIntent showIntent;
    @Deprecated @Nullable public final Handler handler;

    @Deprecated
    public ScheduledAlarm(
        int type, long triggerAtMs, PendingIntent operation, PendingIntent showIntent) {
      this(type, triggerAtMs, 0, operation, showIntent);
    }

    @Deprecated
    public ScheduledAlarm(
        int type,
        long triggerAtMs,
        long intervalMs,
        PendingIntent operation,
        PendingIntent showIntent) {
      this(type, triggerAtMs, intervalMs, operation, showIntent, false);
    }

    @Deprecated
    public ScheduledAlarm(
        int type,
        long triggerAtMs,
        long intervalMs,
        PendingIntent operation,
        PendingIntent showIntent,
        boolean allowWhileIdle) {
      this(
          type,
          triggerAtMs,
          intervalMs,
          WINDOW_HEURISTIC,
          operation,
          null,
          VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && showIntent != null
              ? new AlarmClockInfo(triggerAtMs, showIntent)
              : null,
          allowWhileIdle);
    }

    protected ScheduledAlarm(
        int type,
        long triggerAtMs,
        long windowLengthMs,
        long intervalMs,
        PendingIntent operation,
        @Nullable WorkSource workSource,
        @Nullable Object alarmClockInfo,
        boolean allowWhileIdle) {
      this.type = type;
      this.triggerAtTime = triggerAtMs;
      this.windowLengthMs = windowLengthMs;
      this.interval = intervalMs;
      this.tag = null;
      this.operation = Objects.requireNonNull(operation);
      this.onAlarmListener = null;
      this.executor = null;
      this.workSource = workSource;
      this.alarmClockInfo = alarmClockInfo;
      this.allowWhileIdle = allowWhileIdle;

      this.handler = null;
      if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && alarmClockInfo != null) {
        this.showIntent = ((AlarmClockInfo) alarmClockInfo).getShowIntent();
      } else {
        this.showIntent = null;
      }
    }

    protected ScheduledAlarm(
        int type,
        long triggerAtMs,
        long windowLengthMs,
        long intervalMs,
        @Nullable String tag,
        OnAlarmListener listener,
        Executor executor,
        @Nullable WorkSource workSource,
        @Nullable Object alarmClockInfo,
        boolean allowWhileIdle) {
      this.type = type;
      this.triggerAtTime = triggerAtMs;
      this.windowLengthMs = windowLengthMs;
      this.interval = intervalMs;
      this.tag = tag;
      this.operation = null;
      this.onAlarmListener = Objects.requireNonNull(listener);
      this.executor = Objects.requireNonNull(executor);
      this.workSource = workSource;
      this.alarmClockInfo = alarmClockInfo;
      this.allowWhileIdle = allowWhileIdle;

      if (executor instanceof HandlerExecutor) {
        this.handler = ((HandlerExecutor) executor).handler;
      } else {
        this.handler = null;
      }
      if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && alarmClockInfo != null) {
        this.showIntent = ((AlarmClockInfo) alarmClockInfo).getShowIntent();
      } else {
        this.showIntent = null;
      }
    }

    protected ScheduledAlarm(long triggerAtMs, ScheduledAlarm alarm) {
      this.type = alarm.type;
      this.triggerAtTime = triggerAtMs;
      this.windowLengthMs = alarm.windowLengthMs;
      this.interval = alarm.interval;
      this.tag = alarm.tag;
      this.operation = alarm.operation;
      this.onAlarmListener = alarm.onAlarmListener;
      this.executor = alarm.executor;
      this.workSource = alarm.workSource;
      this.alarmClockInfo = alarm.alarmClockInfo;
      this.allowWhileIdle = alarm.allowWhileIdle;

      this.handler = alarm.handler;
      this.showIntent = alarm.showIntent;
    }

    public int getType() {
      return type;
    }

    public long getTriggerAtMs() {
      return triggerAtTime;
    }

    public long getWindowLengthMs() {
      return windowLengthMs;
    }

    public long getIntervalMs() {
      return interval;
    }

    @Nullable
    public String getTag() {
      return tag;
    }

    @Nullable
    public WorkSource getWorkSource() {
      return workSource;
    }

    @RequiresApi(VERSION_CODES.LOLLIPOP)
    @Nullable
    public AlarmClockInfo getAlarmClockInfo() {
      return (AlarmClockInfo) alarmClockInfo;
    }

    public boolean isAllowWhileIdle() {
      return allowWhileIdle;
    }

    @Override
    public int compareTo(ScheduledAlarm scheduledAlarm) {
      return Long.compare(triggerAtTime, scheduledAlarm.triggerAtTime);
    }
  }

  // wrapper class created because we can't modify ScheduledAlarm without breaking compatibility
  private class InternalScheduledAlarm extends ScheduledAlarm implements Runnable {

    InternalScheduledAlarm(
        int type,
        long triggerAtMs,
        long windowLengthMs,
        long intervalMs,
        PendingIntent operation,
        @Nullable WorkSource workSource,
        @Nullable Object alarmClockInfo,
        boolean allowWhileIdle) {
      super(
          type,
          triggerAtMs,
          windowLengthMs,
          intervalMs,
          operation,
          workSource,
          alarmClockInfo,
          allowWhileIdle);
    }

    InternalScheduledAlarm(
        int type,
        long triggerAtMs,
        long windowLengthMs,
        long intervalMs,
        @Nullable String tag,
        OnAlarmListener listener,
        Executor executor,
        @Nullable WorkSource workSource,
        @Nullable Object alarmClockInfo,
        boolean allowWhileIdle) {
      super(
          type,
          triggerAtMs,
          windowLengthMs,
          intervalMs,
          tag,
          listener,
          executor,
          workSource,
          alarmClockInfo,
          allowWhileIdle);
    }

    InternalScheduledAlarm(long triggerAtMs, InternalScheduledAlarm alarm) {
      super(triggerAtMs, alarm);
    }

    InternalScheduledAlarm schedule() {
      if (autoSchedule) {
        schedulingHandler.postDelayed(this, triggerAtTime - SystemClock.elapsedRealtime());
      }
      return this;
    }

    void deschedule() {
      schedulingHandler.removeCallbacks(this);
    }

    @Override
    public void run() {
      Executor executor;
      if (operation != null) {
        executor = Runnable::run;
      } else {
        executor = Objects.requireNonNull(this.executor);
      }

      executor.execute(
          () -> {
            synchronized (scheduledAlarms) {
              if (!scheduledAlarms.remove(this)) {
                return;
              }
              if (interval > 0) {
                scheduledAlarms.add(
                    new InternalScheduledAlarm(triggerAtTime + interval, this).schedule());
              }
            }
            if (operation != null) {
              try {
                operation.send();
              } catch (CanceledException e) {
                // only necessary in case this is a repeated alarm and we've already rescheduled
                cancel(operation);
              }
            } else if (VERSION.SDK_INT >= VERSION_CODES.N) {
              Objects.requireNonNull(onAlarmListener).onAlarm();
            } else {
              throw new IllegalStateException();
            }
          });
    }
  }

  private static final class HandlerExecutor implements Executor {
    private final Handler handler;

    HandlerExecutor(@Nullable Handler handler) {
      this.handler = handler != null ? handler : new Handler(Looper.getMainLooper());
    }

    @Override
    public void execute(Runnable command) {
      if (!handler.post(command)) {
        throw new RejectedExecutionException(handler + " is shutting down");
      }
    }
  }

  @ForType(AlarmManager.class)
  interface AlarmManagerReflector {

    @Direct
    void setTimeZone(String timeZone);
  }
}