aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowActivity.java
blob: 2c6520d3b039616b76bc66d580b67b13787ad158 (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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.O_MR1;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.annotation.AnimRes;
import android.annotation.ColorInt;
import android.annotation.RequiresApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.ActivityThread;
import android.app.Application;
import android.app.Dialog;
import android.app.DirectAction;
import android.app.Instrumentation;
import android.app.LoadedApk;
import android.app.PendingIntent;
import android.app.PictureInPictureParams;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Binder;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Parcel;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.util.SparseArray;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.android.internal.app.IVoiceInteractor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.RealObject;
import org.robolectric.fakes.RoboIntentSender;
import org.robolectric.fakes.RoboMenuItem;
import org.robolectric.fakes.RoboSplashScreen;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowContextImpl._ContextImpl_;
import org.robolectric.shadows.ShadowInstrumentation.TargetAndRequestCode;
import org.robolectric.shadows.ShadowLoadedApk._LoadedApk_;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.WithType;

@SuppressWarnings("NewApi")
@Implements(value = Activity.class, looseSignatures = true)
public class ShadowActivity extends ShadowContextThemeWrapper {

  @RealObject protected Activity realActivity;

  private int resultCode;
  private Intent resultIntent;
  private Activity parent;
  private int requestedOrientation = -1;
  private View currentFocus;
  private Integer lastShownDialogId = null;
  private int pendingTransitionEnterAnimResId = -1;
  private int pendingTransitionExitAnimResId = -1;
  private SparseArray<OverriddenActivityTransition> overriddenActivityTransitions =
      new SparseArray<>();
  private Object lastNonConfigurationInstance;
  private Map<Integer, Dialog> dialogForId = new HashMap<>();
  private ArrayList<Cursor> managedCursors = new ArrayList<>();
  private int mDefaultKeyMode = Activity.DEFAULT_KEYS_DISABLE;
  private SpannableStringBuilder mDefaultKeySsb = null;
  private int streamType = -1;
  private boolean mIsTaskRoot = true;
  private Menu optionsMenu;
  private ComponentName callingActivity;
  private PermissionsRequest lastRequestedPermission;
  private ActivityController controller;
  private boolean inMultiWindowMode = false;
  private IntentSenderRequest lastIntentSenderRequest;
  private boolean throwIntentSenderException;
  private boolean hasReportedFullyDrawn = false;
  private boolean isInPictureInPictureMode = false;
  private Object splashScreen = null;
  private boolean showWhenLocked = false;
  private boolean turnScreenOn = false;

  public void setApplication(Application application) {
    reflector(_Activity_.class, realActivity).setApplication(application);
  }

  public void callAttach(Intent intent) {
    callAttach(intent, /*activityOptions=*/ null, /*lastNonConfigurationInstances=*/ null);
  }

  public void callAttach(Intent intent, @Nullable Bundle activityOptions) {
    callAttach(
        intent, /*activityOptions=*/ activityOptions, /*lastNonConfigurationInstances=*/ null);
  }

  public void callAttach(
      Intent intent,
      @Nullable Bundle activityOptions,
      @Nullable @WithType("android.app.Activity$NonConfigurationInstances")
          Object lastNonConfigurationInstances) {
    callAttach(
        intent,
        /* activityOptions= */ activityOptions,
        /* lastNonConfigurationInstances= */ null,
        /* overrideConfig= */ null);
  }

  public void callAttach(
      Intent intent,
      @Nullable Bundle activityOptions,
      @Nullable @WithType("android.app.Activity$NonConfigurationInstances")
          Object lastNonConfigurationInstances,
      @Nullable Configuration overrideConfig) {
    Application application = RuntimeEnvironment.getApplication();
    Context baseContext = application.getBaseContext();

    ComponentName componentName =
        new ComponentName(application.getPackageName(), realActivity.getClass().getName());
    ActivityInfo activityInfo;
    PackageManager packageManager = application.getPackageManager();
    shadowOf(packageManager).addActivityIfNotPresent(componentName);
    try {
      activityInfo = packageManager.getActivityInfo(componentName, PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
      throw new RuntimeException("Activity is not resolved even if we made sure it exists", e);
    }
    Binder token = new Binder();

    CharSequence activityTitle = activityInfo.loadLabel(baseContext.getPackageManager());

    ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread();
    Instrumentation instrumentation = activityThread.getInstrumentation();

    Context activityContext;
    int displayId =
        activityOptions != null
            ? ActivityOptions.fromBundle(activityOptions).getLaunchDisplayId()
            : Display.DEFAULT_DISPLAY;
    // There's no particular reason to only do this above O, however the createActivityContext
    // method signature changed between versions so just for convenience only the latest version is
    // plumbed through, older versions will use the previous robolectric behavior of sharing
    // activity and application ContextImpl objects.
    // TODO(paulsowden): This should be enabled always but many service shadows are storing instance
    //  state that should be represented globally, we'll have to update these one by one to use
    //  static (i.e. global) state instead of instance state. For now enable only when the display
    //  is requested to a non-default display which requires a separate context to function
    //  properly.
    if ((Boolean.getBoolean("robolectric.createActivityContexts")
            || (displayId != Display.DEFAULT_DISPLAY && displayId != Display.INVALID_DISPLAY))
        && RuntimeEnvironment.getApiLevel() >= O) {
      LoadedApk loadedApk =
          activityThread.getPackageInfo(
              ShadowActivityThread.getApplicationInfo(), null, Context.CONTEXT_INCLUDE_CODE);
      _LoadedApk_ loadedApkReflector = reflector(_LoadedApk_.class, loadedApk);
      loadedApkReflector.setResources(application.getResources());
      loadedApkReflector.setApplication(application);
      activityContext =
          reflector(_ContextImpl_.class)
              .createActivityContext(
                  activityThread, loadedApk, activityInfo, token, displayId, overrideConfig);
      reflector(_ContextImpl_.class, activityContext).setOuterContext(realActivity);
      // This is not what the SDK does but for backwards compatibility with previous versions of
      // robolectric, which did not use a separate activity context, move the theme from the
      // application context (previously tests would configure the theme on the application context
      // with the expectation that it modify the activity).
      if (baseContext.getThemeResId() != 0) {
        activityContext.setTheme(baseContext.getThemeResId());
      }
    } else {
      activityContext = baseContext;
    }

    reflector(_Activity_.class, realActivity)
        .callAttach(
            realActivity,
            activityContext,
            activityThread,
            instrumentation,
            application,
            intent,
            activityInfo,
            token,
            activityTitle,
            lastNonConfigurationInstances);

    int theme = activityInfo.getThemeResource();
    if (theme != 0) {
      realActivity.setTheme(theme);
    }
  }

  /**
   * Sets the calling activity that will be reflected in {@link Activity#getCallingActivity} and
   * {@link Activity#getCallingPackage}.
   */
  public void setCallingActivity(@Nullable ComponentName activityName) {
    callingActivity = activityName;
  }

  @Implementation
  protected ComponentName getCallingActivity() {
    return callingActivity;
  }

  /**
   * Sets the calling package that will be reflected in {@link Activity#getCallingActivity} and
   * {@link Activity#getCallingPackage}.
   *
   * <p>Activity name defaults to some default value.
   */
  public void setCallingPackage(@Nullable String packageName) {
    if (callingActivity != null && callingActivity.getPackageName().equals(packageName)) {
      // preserve the calling activity as it was, so non-conflicting setCallingActivity followed by
      // setCallingPackage will not erase previously set information.
      return;
    }
    callingActivity =
        packageName != null ? new ComponentName(packageName, "unknown.Activity") : null;
  }

  @Implementation
  protected String getCallingPackage() {
    return callingActivity != null ? callingActivity.getPackageName() : null;
  }

  @Implementation
  protected void setDefaultKeyMode(int keyMode) {
    mDefaultKeyMode = keyMode;

    // Some modes use a SpannableStringBuilder to track & dispatch input events
    // This list must remain in sync with the switch in onKeyDown()
    switch (mDefaultKeyMode) {
      case Activity.DEFAULT_KEYS_DISABLE:
      case Activity.DEFAULT_KEYS_SHORTCUT:
        mDefaultKeySsb = null; // not used in these modes
        break;
      case Activity.DEFAULT_KEYS_DIALER:
      case Activity.DEFAULT_KEYS_SEARCH_LOCAL:
      case Activity.DEFAULT_KEYS_SEARCH_GLOBAL:
        mDefaultKeySsb = new SpannableStringBuilder();
        Selection.setSelection(mDefaultKeySsb, 0);
        break;
      default:
        throw new IllegalArgumentException();
    }
  }

  public int getDefaultKeymode() {
    return mDefaultKeyMode;
  }

  @Implementation(minSdk = O_MR1)
  protected void setShowWhenLocked(boolean showWhenLocked) {
    this.showWhenLocked = showWhenLocked;
  }

  @RequiresApi(api = O_MR1)
  public boolean getShowWhenLocked() {
    return showWhenLocked;
  }

  @Implementation(minSdk = O_MR1)
  protected void setTurnScreenOn(boolean turnScreenOn) {
    this.turnScreenOn = turnScreenOn;
  }

  @RequiresApi(api = O_MR1)
  public boolean getTurnScreenOn() {
    return turnScreenOn;
  }

  @Implementation
  protected final void setResult(int resultCode) {
    this.resultCode = resultCode;
  }

  @Implementation
  protected final void setResult(int resultCode, Intent data) {
    this.resultCode = resultCode;
    this.resultIntent = data;
  }

  @Implementation
  protected LayoutInflater getLayoutInflater() {
    return LayoutInflater.from(realActivity);
  }

  @Implementation
  protected MenuInflater getMenuInflater() {
    return new MenuInflater(realActivity);
  }

  /**
   * Checks to ensure that the{@code contentView} has been set
   *
   * @param id ID of the view to find
   * @return the view
   * @throws RuntimeException if the {@code contentView} has not been called first
   */
  @Implementation
  protected View findViewById(int id) {
    return getWindow().findViewById(id);
  }

  @Implementation
  protected final Activity getParent() {
    return parent;
  }

  /**
   * Allow setting of Parent fragmentActivity (for unit testing purposes only)
   *
   * @param parent Parent fragmentActivity to set on this fragmentActivity
   */
  @HiddenApi
  @Implementation
  public void setParent(Activity parent) {
    this.parent = parent;
  }

  @Implementation
  protected void onBackPressed() {
    finish();
  }

  @Implementation
  protected void finish() {
    // Sets the mFinished field in the real activity so NoDisplay activities can be tested.
    reflector(_Activity_.class, realActivity).setFinished(true);
  }

  @Implementation(minSdk = LOLLIPOP)
  protected void finishAndRemoveTask() {
    // Sets the mFinished field in the real activity so NoDisplay activities can be tested.
    reflector(_Activity_.class, realActivity).setFinished(true);
  }

  @Implementation
  protected void finishAffinity() {
    // Sets the mFinished field in the real activity so NoDisplay activities can be tested.
    reflector(_Activity_.class, realActivity).setFinished(true);
  }

  public void resetIsFinishing() {
    reflector(_Activity_.class, realActivity).setFinished(false);
  }

  /**
   * Returns whether {@link #finish()} was called.
   *
   * <p>Note: this method seems redundant, but removing it will cause problems for Mockito spies of
   * Activities that call {@link Activity#finish()} followed by {@link Activity#isFinishing()}. This
   * is because `finish` modifies the members of {@link ShadowActivity#realActivity}, so
   * `isFinishing` should refer to those same members.
   */
  @Implementation
  protected boolean isFinishing() {
    return reflector(DirectActivityReflector.class, realActivity).isFinishing();
  }

  /**
   * Constructs a new Window (a {@link com.android.internal.policy.impl.PhoneWindow}) if no window
   * has previously been set.
   *
   * @return the window associated with this Activity
   */
  @Implementation
  protected Window getWindow() {
    Window window = reflector(DirectActivityReflector.class, realActivity).getWindow();

    if (window == null) {
      try {
        window = ShadowWindow.create(realActivity);
        setWindow(window);
      } catch (Exception e) {
        throw new RuntimeException("Window creation failed!", e);
      }
    }

    return window;
  }

  /**
   * @return fake SplashScreen
   */
  @Implementation(minSdk = S)
  protected synchronized Object getSplashScreen() {
    if (splashScreen == null) {
      splashScreen = new RoboSplashScreen();
    }
    return splashScreen;
  }

  public void setWindow(Window window) {
    reflector(_Activity_.class, realActivity).setWindow(window);
  }

  @Implementation
  protected void runOnUiThread(Runnable action) {
    if (ShadowLooper.looperMode() == LooperMode.Mode.LEGACY) {
      ShadowApplication.getInstance().getForegroundThreadScheduler().post(action);
    } else {
      reflector(DirectActivityReflector.class, realActivity).runOnUiThread(action);
    }
  }

  @Implementation
  protected void setRequestedOrientation(int requestedOrientation) {
    if (getParent() != null) {
      getParent().setRequestedOrientation(requestedOrientation);
    } else {
      this.requestedOrientation = requestedOrientation;
    }
  }

  @Implementation
  protected int getRequestedOrientation() {
    if (getParent() != null) {
      return getParent().getRequestedOrientation();
    } else {
      return this.requestedOrientation;
    }
  }

  @Implementation
  protected int getTaskId() {
    return 0;
  }

  @Implementation
  public void startIntentSenderForResult(
      IntentSender intentSender,
      int requestCode,
      @Nullable Intent fillInIntent,
      int flagsMask,
      int flagsValues,
      int extraFlags,
      Bundle options)
      throws IntentSender.SendIntentException {
    if (throwIntentSenderException) {
      throw new IntentSender.SendIntentException("PendingIntent was canceled");
    }
    lastIntentSenderRequest =
        new IntentSenderRequest(
            intentSender, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options);
    lastIntentSenderRequest.send();
  }

  @Implementation
  protected void reportFullyDrawn() {
    hasReportedFullyDrawn = true;
  }

  /**
   * @return whether {@code ReportFullyDrawn()} methods has been called.
   */
  public boolean getReportFullyDrawn() {
    return hasReportedFullyDrawn;
  }

  /**
   * @return the {@code contentView} set by one of the {@code setContentView()} methods
   */
  public View getContentView() {
    return ((ViewGroup) getWindow().findViewById(android.R.id.content)).getChildAt(0);
  }

  /**
   * @return the {@code resultCode} set by one of the {@code setResult()} methods
   */
  public int getResultCode() {
    return resultCode;
  }

  /**
   * @return the {@code Intent} set by {@link #setResult(int, android.content.Intent)}
   */
  public Intent getResultIntent() {
    return resultIntent;
  }

  /**
   * Consumes and returns the next {@code Intent} on the started activities for results stack.
   *
   * @return the next started {@code Intent} for an activity, wrapped in an {@link
   *     ShadowActivity.IntentForResult} object
   */
  public IntentForResult getNextStartedActivityForResult() {
    ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread();
    ShadowInstrumentation shadowInstrumentation =
        Shadow.extract(activityThread.getInstrumentation());
    return shadowInstrumentation.getNextStartedActivityForResult();
  }

  /**
   * Returns the most recent {@code Intent} started by {@link
   * Activity#startActivityForResult(Intent, int)} without consuming it.
   *
   * @return the most recently started {@code Intent}, wrapped in an {@link
   *     ShadowActivity.IntentForResult} object
   */
  public IntentForResult peekNextStartedActivityForResult() {
    ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread();
    ShadowInstrumentation shadowInstrumentation =
        Shadow.extract(activityThread.getInstrumentation());
    return shadowInstrumentation.peekNextStartedActivityForResult();
  }

  @Implementation
  protected Object getLastNonConfigurationInstance() {
    if (lastNonConfigurationInstance != null) {
      return lastNonConfigurationInstance;
    }
    return reflector(DirectActivityReflector.class, realActivity).getLastNonConfigurationInstance();
  }

  /**
   * @deprecated use {@link ActivityController#recreate()}.
   */
  @Deprecated
  public void setLastNonConfigurationInstance(Object lastNonConfigurationInstance) {
    this.lastNonConfigurationInstance = lastNonConfigurationInstance;
  }

  /**
   * @param view View to focus.
   */
  public void setCurrentFocus(View view) {
    currentFocus = view;
  }

  @Implementation
  protected View getCurrentFocus() {
    return currentFocus;
  }

  public int getPendingTransitionEnterAnimationResourceId() {
    return pendingTransitionEnterAnimResId;
  }

  public int getPendingTransitionExitAnimationResourceId() {
    return pendingTransitionExitAnimResId;
  }

  /**
   * Get the overridden {@link Activity} transition, set by {@link
   * Activity#overrideActivityTransition}.
   *
   * @param overrideType Use {@link Activity#OVERRIDE_TRANSITION_OPEN} to get the overridden
   *     activity transition animation details when starting/entering an activity. Use {@link
   *     Activity#OVERRIDE_TRANSITION_CLOSE} to get the overridden activity transition animation
   *     details when finishing/closing an activity.
   * @return overridden activity transition details after calling {@link
   *     Activity#overrideActivityTransition(int, int, int, int)} or null if was not overridden.
   * @see #clearOverrideActivityTransition(int)
   */
  @Nullable
  @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
  public OverriddenActivityTransition getOverriddenActivityTransition(int overrideType) {
    return overriddenActivityTransitions.get(overrideType, null);
  }

  @Implementation
  protected boolean onCreateOptionsMenu(Menu menu) {
    optionsMenu = menu;
    return reflector(DirectActivityReflector.class, realActivity).onCreateOptionsMenu(menu);
  }

  /**
   * Return the options menu.
   *
   * @return Options menu.
   */
  public Menu getOptionsMenu() {
    return optionsMenu;
  }

  /**
   * Perform a click on a menu item.
   *
   * @param menuItemResId Menu item resource ID.
   * @return True if the click was handled, false otherwise.
   */
  public boolean clickMenuItem(int menuItemResId) {
    final RoboMenuItem item = new RoboMenuItem(menuItemResId);
    return realActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item);
  }

  @Deprecated
  public void callOnActivityResult(int requestCode, int resultCode, Intent resultData) {
    reflector(_Activity_.class, realActivity).onActivityResult(requestCode, resultCode, resultData);
  }

  /** For internal use only. Not for public use. */
  public void internalCallDispatchActivityResult(
      String who, int requestCode, int resultCode, Intent data) {
    if (VERSION.SDK_INT >= VERSION_CODES.P) {
      reflector(_Activity_.class, realActivity)
          .dispatchActivityResult(who, requestCode, resultCode, data, "ACTIVITY_RESULT");
    } else {
      reflector(_Activity_.class, realActivity)
          .dispatchActivityResult(who, requestCode, resultCode, data);
    }
  }

  /** For internal use only. Not for public use. */
  public <T extends Activity> void attachController(ActivityController controller) {
    this.controller = controller;
  }

  /** Sets if startIntentSenderForRequestCode will throw an IntentSender.SendIntentException. */
  public void setThrowIntentSenderException(boolean throwIntentSenderException) {
    this.throwIntentSenderException = throwIntentSenderException;
  }

  /**
   * Container object to hold an Intent, together with the requestCode used in a call to {@code
   * Activity.startActivityForResult(Intent, int)}
   */
  public static class IntentForResult {
    public Intent intent;
    public int requestCode;
    public Bundle options;

    public IntentForResult(Intent intent, int requestCode) {
      this.intent = intent;
      this.requestCode = requestCode;
      this.options = null;
    }

    public IntentForResult(Intent intent, int requestCode, Bundle options) {
      this.intent = intent;
      this.requestCode = requestCode;
      this.options = options;
    }

    @Override
    public String toString() {
      return super.toString()
          + "{intent="
          + intent
          + ", requestCode="
          + requestCode
          + ", options="
          + options
          + '}';
    }
  }

  public void receiveResult(Intent requestIntent, int resultCode, Intent resultIntent) {
    ActivityThread activityThread = (ActivityThread) RuntimeEnvironment.getActivityThread();
    ShadowInstrumentation shadowInstrumentation =
        Shadow.extract(activityThread.getInstrumentation());
    TargetAndRequestCode targetAndRequestCode =
        shadowInstrumentation.getTargetAndRequestCodeForIntent(requestIntent);

    internalCallDispatchActivityResult(
        targetAndRequestCode.target, targetAndRequestCode.requestCode, resultCode, resultIntent);
  }

  @Implementation
  protected final void showDialog(int id) {
    showDialog(id, null);
  }

  @Implementation
  protected final void dismissDialog(int id) {
    final Dialog dialog = dialogForId.get(id);
    if (dialog == null) {
      throw new IllegalArgumentException();
    }

    dialog.dismiss();
  }

  @Implementation
  protected final void removeDialog(int id) {
    dialogForId.remove(id);
  }

  @Implementation
  protected final boolean showDialog(int id, Bundle bundle) {
    this.lastShownDialogId = id;
    Dialog dialog = dialogForId.get(id);

    if (dialog == null) {
      dialog = reflector(_Activity_.class, realActivity).onCreateDialog(id);
      if (dialog == null) {
        return false;
      }
      if (bundle == null) {
        reflector(_Activity_.class, realActivity).onPrepareDialog(id, dialog);
      } else {
        reflector(_Activity_.class, realActivity).onPrepareDialog(id, dialog, bundle);
      }

      dialogForId.put(id, dialog);
    }

    dialog.show();
    return true;
  }

  public void setIsTaskRoot(boolean isRoot) {
    mIsTaskRoot = isRoot;
  }

  @Implementation
  protected final boolean isTaskRoot() {
    return mIsTaskRoot;
  }

  /**
   * @return the dialog resource id passed into {@code Activity.showDialog(int, Bundle)} or {@code
   *     Activity.showDialog(int)}
   */
  public Integer getLastShownDialogId() {
    return lastShownDialogId;
  }

  public boolean hasCancelledPendingTransitions() {
    return pendingTransitionEnterAnimResId == 0 && pendingTransitionExitAnimResId == 0;
  }

  @Implementation
  protected void overridePendingTransition(int enterAnim, int exitAnim) {
    pendingTransitionEnterAnimResId = enterAnim;
    pendingTransitionExitAnimResId = exitAnim;
  }

  @Implementation(minSdk = UPSIDE_DOWN_CAKE)
  protected void overrideActivityTransition(
      int overrideType,
      @AnimRes int enterAnim,
      @AnimRes int exitAnim,
      @ColorInt int backgroundColor) {
    overriddenActivityTransitions.put(
        overrideType, new OverriddenActivityTransition(enterAnim, exitAnim, backgroundColor));

    reflector(DirectActivityReflector.class, realActivity)
        .overrideActivityTransition(overrideType, enterAnim, exitAnim, backgroundColor);
  }

  @Implementation(minSdk = UPSIDE_DOWN_CAKE)
  protected void clearOverrideActivityTransition(int overrideType) {
    overriddenActivityTransitions.remove(overrideType);

    reflector(DirectActivityReflector.class, realActivity)
        .clearOverrideActivityTransition(overrideType);
  }

  public Dialog getDialogById(int dialogId) {
    return dialogForId.get(dialogId);
  }

  // TODO(hoisie): consider moving this to ActivityController#makeActivityEligibleForGc
  @Implementation
  protected void onDestroy() {
    reflector(DirectActivityReflector.class, realActivity).onDestroy();
    ShadowActivityThread activityThread = Shadow.extract(RuntimeEnvironment.getActivityThread());
    IBinder token = reflector(_Activity_.class, realActivity).getToken();
    activityThread.removeActivity(token);
  }

  @Implementation
  protected void recreate() {
    if (controller != null) {
      // Post the call to recreate to simulate ActivityThread behavior.
      new Handler(Looper.getMainLooper()).post(controller::recreate);
    } else {
      throw new IllegalStateException(
          "Cannot use an Activity that is not managed by an ActivityController");
    }
  }

  @Implementation
  protected void startManagingCursor(Cursor c) {
    managedCursors.add(c);
  }

  @Implementation
  protected void stopManagingCursor(Cursor c) {
    managedCursors.remove(c);
  }

  public List<Cursor> getManagedCursors() {
    return managedCursors;
  }

  @Implementation
  protected final void setVolumeControlStream(int streamType) {
    this.streamType = streamType;
  }

  @Implementation
  protected final int getVolumeControlStream() {
    return streamType;
  }

  @Implementation(minSdk = M)
  protected final void requestPermissions(String[] permissions, int requestCode) {
    lastRequestedPermission = new PermissionsRequest(permissions, requestCode);
    reflector(DirectActivityReflector.class, realActivity)
        .requestPermissions(permissions, requestCode);
  }

  /**
   * Starts a lock task.
   *
   * <p>The status of the lock task can be verified using {@link #isLockTask} method. Otherwise this
   * implementation has no effect.
   */
  @Implementation(minSdk = LOLLIPOP)
  protected void startLockTask() {
    Shadow.<ShadowActivityManager>extract(getActivityManager())
        .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_LOCKED);
  }

  /**
   * Stops a lock task.
   *
   * <p>The status of the lock task can be verified using {@link #isLockTask} method. Otherwise this
   * implementation has no effect.
   */
  @Implementation(minSdk = LOLLIPOP)
  protected void stopLockTask() {
    Shadow.<ShadowActivityManager>extract(getActivityManager())
        .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_NONE);
  }

  /**
   * Returns if the activity is in the lock task mode.
   *
   * @deprecated Use {@link ActivityManager#getLockTaskModeState} instead.
   */
  @Deprecated
  public boolean isLockTask() {
    return getActivityManager().isInLockTaskMode();
  }

  private ActivityManager getActivityManager() {
    return (ActivityManager) realActivity.getSystemService(Context.ACTIVITY_SERVICE);
  }

  /** Changes state of {@link #isInMultiWindowMode} method. */
  public void setInMultiWindowMode(boolean value) {
    inMultiWindowMode = value;
  }

  @Implementation(minSdk = N)
  protected boolean isInMultiWindowMode() {
    return inMultiWindowMode;
  }

  @Implementation(minSdk = N)
  protected boolean isInPictureInPictureMode() {
    return isInPictureInPictureMode;
  }

  @Implementation(minSdk = N)
  protected void enterPictureInPictureMode() {
    isInPictureInPictureMode = true;
  }

  @Implementation(minSdk = O)
  protected boolean enterPictureInPictureMode(PictureInPictureParams params) {
    isInPictureInPictureMode = true;
    return true;
  }

  @Implementation
  protected boolean moveTaskToBack(boolean nonRoot) {
    isInPictureInPictureMode = false;
    return true;
  }

  /**
   * Gets the last startIntentSenderForResult request made to this activity.
   *
   * @return The IntentSender request details.
   */
  public IntentSenderRequest getLastIntentSenderRequest() {
    return lastIntentSenderRequest;
  }

  /**
   * Gets the last permission request submitted to this activity.
   *
   * @return The permission request details.
   */
  public PermissionsRequest getLastRequestedPermission() {
    return lastRequestedPermission;
  }

  /**
   * Initializes the associated Activity with an {@link android.app.VoiceInteractor} instance.
   * Subsequent {@link android.app.Activity#getVoiceInteractor()} calls on the associated activity
   * will return a {@link android.app.VoiceInteractor} instance
   */
  public void initializeVoiceInteractor() {
    if (RuntimeEnvironment.getApiLevel() < N) {
      throw new IllegalStateException("initializeVoiceInteractor requires API " + N);
    }
    reflector(_Activity_.class, realActivity)
        .setVoiceInteractor(ReflectionHelpers.createDeepProxy(IVoiceInteractor.class));
  }

  /**
   * Calls Activity#onGetDirectActions with the given parameters. This method also simulates the
   * Parcel serialization/deserialization which occurs when assistant requests DirectAction.
   */
  public void callOnGetDirectActions(
      CancellationSignal cancellationSignal, Consumer<List<DirectAction>> callback) {
    if (RuntimeEnvironment.getApiLevel() < Q) {
      throw new IllegalStateException("callOnGetDirectActions requires API " + Q);
    }
    realActivity.onGetDirectActions(
        cancellationSignal,
        directActions -> {
          Parcel parcel = Parcel.obtain();
          parcel.writeParcelableList(directActions, 0);
          parcel.setDataPosition(0);
          List<DirectAction> output = new ArrayList<>();
          parcel.readParcelableList(output, DirectAction.class.getClassLoader());
          callback.accept(output);
        });
  }

  /**
   * Class to hold overridden activity transition details after calling {@link
   * Activity#overrideActivityTransition(int, int, int, int)}
   */
  public static class OverriddenActivityTransition {
    @AnimRes public final int enterAnim;
    @AnimRes public final int exitAnim;
    @ColorInt public final int backgroundColor;

    public OverriddenActivityTransition(int enterAnim, int exitAnim, int backgroundColor) {
      this.enterAnim = enterAnim;
      this.exitAnim = exitAnim;
      this.backgroundColor = backgroundColor;
    }
  }

  /** Class to hold a permissions request, including its request code. */
  public static class PermissionsRequest {
    public final int requestCode;
    public final String[] requestedPermissions;

    public PermissionsRequest(String[] requestedPermissions, int requestCode) {
      this.requestedPermissions = requestedPermissions;
      this.requestCode = requestCode;
    }
  }

  /** Class to holds details of a startIntentSenderForResult request. */
  public static class IntentSenderRequest {
    public final IntentSender intentSender;
    public final int requestCode;
    @Nullable public final Intent fillInIntent;
    public final int flagsMask;
    public final int flagsValues;
    public final int extraFlags;
    public final Bundle options;

    public IntentSenderRequest(
        IntentSender intentSender,
        int requestCode,
        @Nullable Intent fillInIntent,
        int flagsMask,
        int flagsValues,
        int extraFlags,
        Bundle options) {
      this.intentSender = intentSender;
      this.requestCode = requestCode;
      this.fillInIntent = fillInIntent;
      this.flagsMask = flagsMask;
      this.flagsValues = flagsValues;
      this.extraFlags = extraFlags;
      this.options = options;
    }

    public void send() {
      if (intentSender instanceof RoboIntentSender) {
        try {
          Shadow.<ShadowPendingIntent>extract(((RoboIntentSender) intentSender).getPendingIntent())
              .send(
                  RuntimeEnvironment.getApplication(),
                  0,
                  null,
                  null,
                  null,
                  null,
                  null,
                  requestCode);
        } catch (PendingIntent.CanceledException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  private ShadowPackageManager shadowOf(PackageManager packageManager) {
    return Shadow.extract(packageManager);
  }

  @ForType(value = Activity.class, direct = true)
  interface DirectActivityReflector {

    void runOnUiThread(Runnable action);

    void onDestroy();

    boolean isFinishing();

    void overrideActivityTransition(
        int overrideType, int enterAnim, int exitAnim, int backgroundColor);

    void clearOverrideActivityTransition(int overrideType);

    Window getWindow();

    Object getLastNonConfigurationInstance();

    boolean onCreateOptionsMenu(Menu menu);

    void requestPermissions(String[] permissions, int requestCode);
  }
}