-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
FlutterFragment.java
1412 lines (1313 loc) · 57.3 KB
/
FlutterFragment.java
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
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.android;
import android.app.Activity;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener;
import io.flutter.plugin.platform.PlatformPlugin;
import io.flutter.util.ViewUtils;
import java.util.ArrayList;
import java.util.List;
/**
* {@code Fragment} which displays a Flutter UI that takes up all available {@code Fragment} space.
*
* <p>Using a {@code FlutterFragment} requires forwarding a number of calls from an {@code Activity}
* to ensure that the internal Flutter app behaves as expected:
*
* <ol>
* <li>{@link #onPostResume()}
* <li>{@link #onBackPressed()}
* <li>{@link #onRequestPermissionsResult(int, String[], int[])}
* <li>{@link #onNewIntent(Intent)}
* <li>{@link #onUserLeaveHint()}
* </ol>
*
* {@link #onBackPressed()} does not need to be called through if the fragment is constructed by one
* of the builders with {@code shouldAutomaticallyHandleOnBackPressed(true)}.
*
* <p>Additionally, when starting an {@code Activity} for a result from this {@code Fragment}, be
* sure to invoke {@link Fragment#startActivityForResult(Intent, int)} rather than {@link
* android.app.Activity#startActivityForResult(Intent, int)}. If the {@code Activity} version of the
* method is invoked then this {@code Fragment} will never receive its {@link
* Fragment#onActivityResult(int, int, Intent)} callback.
*
* <p>If convenient, consider using a {@link FlutterActivity} instead of a {@code FlutterFragment}
* to avoid the work of forwarding calls.
*
* <p>{@code FlutterFragment} supports the use of an existing, cached {@link
* io.flutter.embedding.engine.FlutterEngine}. To use a cached {@link
* io.flutter.embedding.engine.FlutterEngine}, ensure that the {@link
* io.flutter.embedding.engine.FlutterEngine} is stored in {@link
* io.flutter.embedding.engine.FlutterEngineCache} and then use {@link #withCachedEngine(String)} to
* build a {@code FlutterFragment} with the cached {@link
* io.flutter.embedding.engine.FlutterEngine}'s ID.
*
* <p>It is generally recommended to use a cached {@link io.flutter.embedding.engine.FlutterEngine}
* to avoid a momentary delay when initializing a new {@link
* io.flutter.embedding.engine.FlutterEngine}. The two exceptions to using a cached {@link
* FlutterEngine} are:
*
* <ul>
* <li>When {@code FlutterFragment} is in the first {@code Activity} displayed by the app, because
* pre-warming a {@link io.flutter.embedding.engine.FlutterEngine} would have no impact in
* this situation.
* <li>When you are unsure when/if you will need to display a Flutter experience.
* </ul>
*
* <p>The following illustrates how to pre-warm and cache a {@link
* io.flutter.embedding.engine.FlutterEngine}:
*
* <pre>{@code
* // Create and pre-warm a FlutterEngine.
* FlutterEngineGroup group = new FlutterEngineGroup(context);
* FlutterEngine flutterEngine = group.createAndRunDefaultEngine(context);
* flutterEngine
* .getDartExecutor()
* .executeDartEntrypoint(DartEntrypoint.createDefault());
*
* // Cache the pre-warmed FlutterEngine in the FlutterEngineCache.
* FlutterEngineCache.getInstance().put("my_engine", flutterEngine);
* }</pre>
*
* <p>If Flutter is needed in a location that can only use a {@code View}, consider using a {@link
* io.flutter.embedding.android.FlutterView}. Using a {@link
* io.flutter.embedding.android.FlutterView} requires forwarding some calls from an {@code
* Activity}, as well as forwarding lifecycle calls from an {@code Activity} or a {@code Fragment}.
*/
public class FlutterFragment extends Fragment
implements FlutterActivityAndFragmentDelegate.Host,
ComponentCallbacks2,
FlutterActivityAndFragmentDelegate.DelegateFactory {
/**
* The ID of the {@code FlutterView} created by this activity.
*
* <p>This ID can be used to lookup {@code FlutterView} in the Android view hierarchy. For more,
* see {@link android.view.View#findViewById}.
*/
public static final int FLUTTER_VIEW_ID = ViewUtils.generateViewId(0xF1F2);
private static final String TAG = "FlutterFragment";
/** The Dart entrypoint method name that is executed upon initialization. */
protected static final String ARG_DART_ENTRYPOINT = "dart_entrypoint";
/** The Dart entrypoint method's URI that is executed upon initialization. */
protected static final String ARG_DART_ENTRYPOINT_URI = "dart_entrypoint_uri";
/** The Dart entrypoint arguments that is executed upon initialization. */
protected static final String ARG_DART_ENTRYPOINT_ARGS = "dart_entrypoint_args";
/** Initial Flutter route that is rendered in a Navigator widget. */
protected static final String ARG_INITIAL_ROUTE = "initial_route";
/** Whether the activity delegate should handle the deeplinking request. */
protected static final String ARG_HANDLE_DEEPLINKING = "handle_deeplinking";
/** Path to Flutter's Dart code. */
protected static final String ARG_APP_BUNDLE_PATH = "app_bundle_path";
/** Whether to delay the Android drawing pass till after the Flutter UI has been displayed. */
protected static final String ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW =
"should_delay_first_android_view_draw";
/** Flutter shell arguments. */
protected static final String ARG_FLUTTER_INITIALIZATION_ARGS = "initialization_args";
/**
* {@link RenderMode} to be used for the {@link io.flutter.embedding.android.FlutterView} in this
* {@code FlutterFragment}
*/
protected static final String ARG_FLUTTERVIEW_RENDER_MODE = "flutterview_render_mode";
/**
* {@link TransparencyMode} to be used for the {@link io.flutter.embedding.android.FlutterView} in
* this {@code FlutterFragment}
*/
protected static final String ARG_FLUTTERVIEW_TRANSPARENCY_MODE = "flutterview_transparency_mode";
/** See {@link #shouldAttachEngineToActivity()}. */
protected static final String ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY =
"should_attach_engine_to_activity";
/**
* The ID of a {@link io.flutter.embedding.engine.FlutterEngine} cached in {@link
* io.flutter.embedding.engine.FlutterEngineCache} that will be used within the created {@code
* FlutterFragment}.
*/
protected static final String ARG_CACHED_ENGINE_ID = "cached_engine_id";
/**
* True if the {@link io.flutter.embedding.engine.FlutterEngine} in the created {@code
* FlutterFragment} should be destroyed when the {@code FlutterFragment} is destroyed, false if
* the {@link io.flutter.embedding.engine.FlutterEngine} should outlive the {@code
* FlutterFragment}.
*/
protected static final String ARG_DESTROY_ENGINE_WITH_FRAGMENT = "destroy_engine_with_fragment";
/**
* True if the framework state in the engine attached to this engine should be stored and restored
* when this fragment is created and destroyed.
*/
protected static final String ARG_ENABLE_STATE_RESTORATION = "enable_state_restoration";
/**
* True if the fragment should receive {@link #onBackPressed()} events automatically, without
* requiring an explicit activity call through.
*/
protected static final String ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED =
"should_automatically_handle_on_back_pressed";
/**
* Creates a {@code FlutterFragment} with a default configuration.
*
* <p>{@code FlutterFragment}'s default configuration creates a new {@link
* io.flutter.embedding.engine.FlutterEngine} within the {@code FlutterFragment} and uses the
* following settings:
*
* <ul>
* <li>Dart entrypoint: "main"
* <li>Initial route: "/"
* <li>Render mode: surface
* <li>Transparency mode: transparent
* </ul>
*
* <p>To use a new {@link io.flutter.embedding.engine.FlutterEngine} with different settings, use
* {@link #withNewEngine()}.
*
* <p>To use a cached {@link io.flutter.embedding.engine.FlutterEngine} instead of creating a new
* one, use {@link #withCachedEngine(String)}.
*/
@NonNull
public static FlutterFragment createDefault() {
return new NewEngineFragmentBuilder().build();
}
/**
* Returns a {@link NewEngineFragmentBuilder} to create a {@code FlutterFragment} with a new
* {@link io.flutter.embedding.engine.FlutterEngine} and a desired engine configuration.
*/
@NonNull
public static NewEngineFragmentBuilder withNewEngine() {
return new NewEngineFragmentBuilder();
}
/**
* Builder that creates a new {@code FlutterFragment} with {@code arguments} that correspond to
* the values set on this {@code NewEngineFragmentBuilder}.
*
* <p>To create a {@code FlutterFragment} with default {@code arguments}, invoke {@link
* #createDefault()}.
*
* <p>Subclasses of {@code FlutterFragment} that do not introduce any new arguments can use this
* {@code NewEngineFragmentBuilder} to construct instances of the subclass without subclassing
* this {@code NewEngineFragmentBuilder}. {@code MyFlutterFragment f = new
* FlutterFragment.NewEngineFragmentBuilder(MyFlutterFragment.class) .someProperty(...)
* .someOtherProperty(...) .build<MyFlutterFragment>(); }
*
* <p>Subclasses of {@code FlutterFragment} that introduce new arguments should subclass this
* {@code NewEngineFragmentBuilder} to add the new properties:
*
* <ol>
* <li>Ensure the {@code FlutterFragment} subclass has a no-arg constructor.
* <li>Subclass this {@code NewEngineFragmentBuilder}.
* <li>Override the new {@code NewEngineFragmentBuilder}'s no-arg constructor and invoke the
* super constructor to set the {@code FlutterFragment} subclass: {@code public MyBuilder()
* { super(MyFlutterFragment.class); } }
* <li>Add appropriate property methods for the new properties.
* <li>Override {@link NewEngineFragmentBuilder#createArgs()}, call through to the super method,
* then add the new properties as arguments in the {@link Bundle}.
* </ol>
*
* Once a {@code NewEngineFragmentBuilder} subclass is defined, the {@code FlutterFragment}
* subclass can be instantiated as follows. {@code MyFlutterFragment f = new MyBuilder()
* .someExistingProperty(...) .someNewProperty(...) .build<MyFlutterFragment>(); }
*/
public static class NewEngineFragmentBuilder {
private final Class<? extends FlutterFragment> fragmentClass;
private String dartEntrypoint = "main";
private String dartLibraryUri = null;
private List<String> dartEntrypointArgs;
private String initialRoute = "/";
private boolean handleDeeplinking = false;
private String appBundlePath = null;
private FlutterShellArgs shellArgs = null;
private RenderMode renderMode = RenderMode.surface;
private TransparencyMode transparencyMode = TransparencyMode.transparent;
private boolean shouldAttachEngineToActivity = true;
private boolean shouldAutomaticallyHandleOnBackPressed = false;
private boolean shouldDelayFirstAndroidViewDraw = false;
/**
* Constructs a {@code NewEngineFragmentBuilder} that is configured to construct an instance of
* {@code FlutterFragment}.
*/
public NewEngineFragmentBuilder() {
fragmentClass = FlutterFragment.class;
}
/**
* Constructs a {@code NewEngineFragmentBuilder} that is configured to construct an instance of
* {@code subclass}, which extends {@code FlutterFragment}.
*/
public NewEngineFragmentBuilder(@NonNull Class<? extends FlutterFragment> subclass) {
fragmentClass = subclass;
}
/** The name of the initial Dart method to invoke, defaults to "main". */
@NonNull
public NewEngineFragmentBuilder dartEntrypoint(@NonNull String dartEntrypoint) {
this.dartEntrypoint = dartEntrypoint;
return this;
}
@NonNull
public NewEngineFragmentBuilder dartLibraryUri(@NonNull String dartLibraryUri) {
this.dartLibraryUri = dartLibraryUri;
return this;
}
/** Arguments passed as a list of string to Dart's entrypoint function. */
@NonNull
public NewEngineFragmentBuilder dartEntrypointArgs(@NonNull List<String> dartEntrypointArgs) {
this.dartEntrypointArgs = dartEntrypointArgs;
return this;
}
/**
* The initial route that a Flutter app will render in this {@link FlutterFragment}, defaults to
* "/".
*/
@NonNull
public NewEngineFragmentBuilder initialRoute(@NonNull String initialRoute) {
this.initialRoute = initialRoute;
return this;
}
/**
* Whether to handle the deeplinking from the {@code Intent} automatically if the {@code
* getInitialRoute} returns null.
*/
@NonNull
public NewEngineFragmentBuilder handleDeeplinking(@NonNull Boolean handleDeeplinking) {
this.handleDeeplinking = handleDeeplinking;
return this;
}
/**
* The path to the app bundle which contains the Dart app to execute. Null when unspecified,
* which defaults to {@link
* io.flutter.embedding.engine.loader.FlutterLoader#findAppBundlePath()}
*/
@NonNull
public NewEngineFragmentBuilder appBundlePath(@NonNull String appBundlePath) {
this.appBundlePath = appBundlePath;
return this;
}
/** Any special configuration arguments for the Flutter engine */
@NonNull
public NewEngineFragmentBuilder flutterShellArgs(@NonNull FlutterShellArgs shellArgs) {
this.shellArgs = shellArgs;
return this;
}
/**
* Render Flutter either as a {@link RenderMode#surface} or a {@link RenderMode#texture}. You
* should use {@code surface} unless you have a specific reason to use {@code texture}. {@code
* texture} comes with a significant performance impact, but {@code texture} can be displayed
* beneath other Android {@code View}s and animated, whereas {@code surface} cannot.
*/
@NonNull
public NewEngineFragmentBuilder renderMode(@NonNull RenderMode renderMode) {
this.renderMode = renderMode;
return this;
}
/**
* Support a {@link TransparencyMode#transparent} background within {@link
* io.flutter.embedding.android.FlutterView}, or force an {@link TransparencyMode#opaque}
* background.
*
* <p>See {@link TransparencyMode} for implications of this selection.
*/
@NonNull
public NewEngineFragmentBuilder transparencyMode(@NonNull TransparencyMode transparencyMode) {
this.transparencyMode = transparencyMode;
return this;
}
/**
* Whether or not this {@code FlutterFragment} should automatically attach its {@code Activity}
* as a control surface for its {@link io.flutter.embedding.engine.FlutterEngine}.
*
* <p>Control surfaces are used to provide Android resources and lifecycle events to plugins
* that are attached to the {@link io.flutter.embedding.engine.FlutterEngine}. If {@code
* shouldAttachEngineToActivity} is true then this {@code FlutterFragment} will connect its
* {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code Activity}, along
* with any plugins that are registered with that {@link FlutterEngine}. This allows plugins to
* access the {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link
* android.app.Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false,
* then this {@code FlutterFragment} will not automatically manage the connection between its
* {@link io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. The
* {@code Activity} will need to be manually connected to this {@code FlutterFragment}'s {@link
* io.flutter.embedding.engine.FlutterEngine} by the app developer. See {@link
* FlutterEngine#getActivityControlSurface()}.
*
* <p>One reason that a developer might choose to manually manage the relationship between the
* {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the developer
* wants to move the {@link FlutterEngine} somewhere else. For example, a developer might want
* the {@link io.flutter.embedding.engine.FlutterEngine} to outlive the surrounding {@code
* Activity} so that it can be used later in a different {@code Activity}. To accomplish this,
* the {@link io.flutter.embedding.engine.FlutterEngine} will need to be disconnected from the
* surrounding {@code Activity} at an unusual time, preventing this {@code FlutterFragment} from
* correctly managing the relationship between the {@link
* io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}.
*
* <p>Another reason that a developer might choose to manually manage the relationship between
* the {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the
* developer wants to prevent, or explicitly control when the {@link
* io.flutter.embedding.engine.FlutterEngine}'s plugins have access to the surrounding {@code
* Activity}. For example, imagine that this {@code FlutterFragment} only takes up part of the
* screen and the app developer wants to ensure that none of the Flutter plugins are able to
* manipulate the surrounding {@code Activity}. In this case, the developer would not want the
* {@link io.flutter.embedding.engine.FlutterEngine} to have access to the {@code Activity},
* which can be accomplished by setting {@code shouldAttachEngineToActivity} to {@code false}.
*/
@NonNull
public NewEngineFragmentBuilder shouldAttachEngineToActivity(
boolean shouldAttachEngineToActivity) {
this.shouldAttachEngineToActivity = shouldAttachEngineToActivity;
return this;
}
/**
* Whether or not this {@code FlutterFragment} should automatically receive {@link
* #onBackPressed()} events, rather than requiring an explicit activity call through. Disabled
* by default.
*
* <p>When enabled, the activity will automatically dispatch back-press events to the fragment's
* {@link OnBackPressedCallback}, instead of requiring the activity to manually call {@link
* #onBackPressed()} in client code. If enabled, do <b>not</b> invoke {@link #onBackPressed()}
* manually.
*
* <p>This behavior relies on the implementation of {@link #popSystemNavigator()}. It's not
* recommended to override that method when enabling this attribute, but if you do, you should
* always fall back to calling {@code super.popSystemNavigator()} when not relying on custom
* behavior.
*/
@NonNull
public NewEngineFragmentBuilder shouldAutomaticallyHandleOnBackPressed(
boolean shouldAutomaticallyHandleOnBackPressed) {
this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed;
return this;
}
/**
* Whether to delay the Android drawing pass till after the Flutter UI has been displayed.
*
* <p>See {#link FlutterActivityAndFragmentDelegate#onCreateView} for more details.
*/
@NonNull
public NewEngineFragmentBuilder shouldDelayFirstAndroidViewDraw(
boolean shouldDelayFirstAndroidViewDraw) {
this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw;
return this;
}
/**
* Creates a {@link Bundle} of arguments that are assigned to the new {@code FlutterFragment}.
*
* <p>Subclasses should override this method to add new properties to the {@link Bundle}.
* Subclasses must call through to the super method to collect all existing property values.
*/
@NonNull
protected Bundle createArgs() {
Bundle args = new Bundle();
args.putString(ARG_INITIAL_ROUTE, initialRoute);
args.putBoolean(ARG_HANDLE_DEEPLINKING, handleDeeplinking);
args.putString(ARG_APP_BUNDLE_PATH, appBundlePath);
args.putString(ARG_DART_ENTRYPOINT, dartEntrypoint);
args.putString(ARG_DART_ENTRYPOINT_URI, dartLibraryUri);
args.putStringArrayList(
ARG_DART_ENTRYPOINT_ARGS,
dartEntrypointArgs != null ? new ArrayList(dartEntrypointArgs) : null);
// TODO(mattcarroll): determine if we should have an explicit FlutterTestFragment instead of
// conflating.
if (null != shellArgs) {
args.putStringArray(ARG_FLUTTER_INITIALIZATION_ARGS, shellArgs.toArray());
}
args.putString(
ARG_FLUTTERVIEW_RENDER_MODE,
renderMode != null ? renderMode.name() : RenderMode.surface.name());
args.putString(
ARG_FLUTTERVIEW_TRANSPARENCY_MODE,
transparencyMode != null ? transparencyMode.name() : TransparencyMode.transparent.name());
args.putBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY, shouldAttachEngineToActivity);
args.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, true);
args.putBoolean(
ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, shouldAutomaticallyHandleOnBackPressed);
args.putBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW, shouldDelayFirstAndroidViewDraw);
return args;
}
/**
* Constructs a new {@code FlutterFragment} (or a subclass) that is configured based on
* properties set on this {@code Builder}.
*/
@NonNull
public <T extends FlutterFragment> T build() {
try {
@SuppressWarnings("unchecked")
T frag = (T) fragmentClass.getDeclaredConstructor().newInstance();
if (frag == null) {
throw new RuntimeException(
"The FlutterFragment subclass sent in the constructor ("
+ fragmentClass.getCanonicalName()
+ ") does not match the expected return type.");
}
Bundle args = createArgs();
frag.setArguments(args);
return frag;
} catch (Exception e) {
throw new RuntimeException(
"Could not instantiate FlutterFragment subclass (" + fragmentClass.getName() + ")", e);
}
}
}
/**
* Returns a {@link CachedEngineFragmentBuilder} to create a {@code FlutterFragment} with a cached
* {@link io.flutter.embedding.engine.FlutterEngine} in {@link
* io.flutter.embedding.engine.FlutterEngineCache}.
*
* <p>An {@code IllegalStateException} will be thrown during the lifecycle of the {@code
* FlutterFragment} if a cached {@link io.flutter.embedding.engine.FlutterEngine} is requested but
* does not exist in the cache.
*
* <p>To create a {@code FlutterFragment} that uses a new {@link
* io.flutter.embedding.engine.FlutterEngine}, use {@link #createDefault()} or {@link
* #withNewEngine()}.
*/
@NonNull
public static CachedEngineFragmentBuilder withCachedEngine(@NonNull String engineId) {
return new CachedEngineFragmentBuilder(engineId);
}
/**
* Builder that creates a new {@code FlutterFragment} that uses a cached {@link
* io.flutter.embedding.engine.FlutterEngine} with {@code arguments} that correspond to the values
* set on this {@code Builder}.
*
* <p>Subclasses of {@code FlutterFragment} that do not introduce any new arguments can use this
* {@code Builder} to construct instances of the subclass without subclassing this {@code
* Builder}. {@code MyFlutterFragment f = new
* FlutterFragment.CachedEngineFragmentBuilder(MyFlutterFragment.class) .someProperty(...)
* .someOtherProperty(...) .build<MyFlutterFragment>(); }
*
* <p>Subclasses of {@code FlutterFragment} that introduce new arguments should subclass this
* {@code CachedEngineFragmentBuilder} to add the new properties:
*
* <ol>
* <li>Ensure the {@code FlutterFragment} subclass has a no-arg constructor.
* <li>Subclass this {@code CachedEngineFragmentBuilder}.
* <li>Override the new {@code CachedEngineFragmentBuilder}'s no-arg constructor and invoke the
* super constructor to set the {@code FlutterFragment} subclass: {@code public MyBuilder()
* { super(MyFlutterFragment.class); } }
* <li>Add appropriate property methods for the new properties.
* <li>Override {@link CachedEngineFragmentBuilder#createArgs()}, call through to the super
* method, then add the new properties as arguments in the {@link Bundle}.
* </ol>
*
* Once a {@code CachedEngineFragmentBuilder} subclass is defined, the {@code FlutterFragment}
* subclass can be instantiated as follows. {@code MyFlutterFragment f = new MyBuilder()
* .someExistingProperty(...) .someNewProperty(...) .build<MyFlutterFragment>(); }
*/
public static class CachedEngineFragmentBuilder {
private final Class<? extends FlutterFragment> fragmentClass;
private final String engineId;
private boolean destroyEngineWithFragment = false;
private boolean handleDeeplinking = false;
private RenderMode renderMode = RenderMode.surface;
private TransparencyMode transparencyMode = TransparencyMode.transparent;
private boolean shouldAttachEngineToActivity = true;
private boolean shouldAutomaticallyHandleOnBackPressed = false;
private boolean shouldDelayFirstAndroidViewDraw = false;
private CachedEngineFragmentBuilder(@NonNull String engineId) {
this(FlutterFragment.class, engineId);
}
public CachedEngineFragmentBuilder(
@NonNull Class<? extends FlutterFragment> subclass, @NonNull String engineId) {
this.fragmentClass = subclass;
this.engineId = engineId;
}
/**
* Pass {@code true} to destroy the cached {@link io.flutter.embedding.engine.FlutterEngine}
* when this {@code FlutterFragment} is destroyed, or {@code false} for the cached {@link
* io.flutter.embedding.engine.FlutterEngine} to outlive this {@code FlutterFragment}.
*/
@NonNull
public CachedEngineFragmentBuilder destroyEngineWithFragment(
boolean destroyEngineWithFragment) {
this.destroyEngineWithFragment = destroyEngineWithFragment;
return this;
}
/**
* Render Flutter either as a {@link RenderMode#surface} or a {@link RenderMode#texture}. You
* should use {@code surface} unless you have a specific reason to use {@code texture}. {@code
* texture} comes with a significant performance impact, but {@code texture} can be displayed
* beneath other Android {@code View}s and animated, whereas {@code surface} cannot.
*/
@NonNull
public CachedEngineFragmentBuilder renderMode(@NonNull RenderMode renderMode) {
this.renderMode = renderMode;
return this;
}
/**
* Support a {@link TransparencyMode#transparent} background within {@link
* io.flutter.embedding.android.FlutterView}, or force an {@link TransparencyMode#opaque}
* background.
*
* <p>See {@link TransparencyMode} for implications of this selection.
*/
@NonNull
public CachedEngineFragmentBuilder transparencyMode(
@NonNull TransparencyMode transparencyMode) {
this.transparencyMode = transparencyMode;
return this;
}
/**
* Whether to handle the deeplinking from the {@code Intent} automatically if the {@code
* getInitialRoute} returns null.
*/
@NonNull
public CachedEngineFragmentBuilder handleDeeplinking(@NonNull Boolean handleDeeplinking) {
this.handleDeeplinking = handleDeeplinking;
return this;
}
/**
* Whether or not this {@code FlutterFragment} should automatically attach its {@code Activity}
* as a control surface for its {@link io.flutter.embedding.engine.FlutterEngine}.
*
* <p>Control surfaces are used to provide Android resources and lifecycle events to plugins
* that are attached to the {@link io.flutter.embedding.engine.FlutterEngine}. If {@code
* shouldAttachEngineToActivity} is true then this {@code FlutterFragment} will connect its
* {@link io.flutter.embedding.engine.FlutterEngine} to the surrounding {@code Activity}, along
* with any plugins that are registered with that {@link FlutterEngine}. This allows plugins to
* access the {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link
* android.app.Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false,
* then this {@code FlutterFragment} will not automatically manage the connection between its
* {@link io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}. The
* {@code Activity} will need to be manually connected to this {@code FlutterFragment}'s {@link
* io.flutter.embedding.engine.FlutterEngine} by the app developer. See {@link
* FlutterEngine#getActivityControlSurface()}.
*
* <p>One reason that a developer might choose to manually manage the relationship between the
* {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the developer
* wants to move the {@link FlutterEngine} somewhere else. For example, a developer might want
* the {@link io.flutter.embedding.engine.FlutterEngine} to outlive the surrounding {@code
* Activity} so that it can be used later in a different {@code Activity}. To accomplish this,
* the {@link io.flutter.embedding.engine.FlutterEngine} will need to be disconnected from the
* surrounding {@code Activity} at an unusual time, preventing this {@code FlutterFragment} from
* correctly managing the relationship between the {@link
* io.flutter.embedding.engine.FlutterEngine} and the surrounding {@code Activity}.
*
* <p>Another reason that a developer might choose to manually manage the relationship between
* the {@code Activity} and {@link io.flutter.embedding.engine.FlutterEngine} is if the
* developer wants to prevent, or explicitly control when the {@link
* io.flutter.embedding.engine.FlutterEngine}'s plugins have access to the surrounding {@code
* Activity}. For example, imagine that this {@code FlutterFragment} only takes up part of the
* screen and the app developer wants to ensure that none of the Flutter plugins are able to
* manipulate the surrounding {@code Activity}. In this case, the developer would not want the
* {@link io.flutter.embedding.engine.FlutterEngine} to have access to the {@code Activity},
* which can be accomplished by setting {@code shouldAttachEngineToActivity} to {@code false}.
*/
@NonNull
public CachedEngineFragmentBuilder shouldAttachEngineToActivity(
boolean shouldAttachEngineToActivity) {
this.shouldAttachEngineToActivity = shouldAttachEngineToActivity;
return this;
}
/**
* Whether or not this {@code FlutterFragment} should automatically receive {@link
* #onBackPressed()} events, rather than requiring an explicit activity call through. Disabled
* by default.
*
* <p>When enabled, the activity will automatically dispatch back-press events to the fragment's
* {@link OnBackPressedCallback}, instead of requiring the activity to manually call {@link
* #onBackPressed()} in client code. If enabled, do <b>not</b> invoke {@link #onBackPressed()}
* manually.
*
* <p>Enabling this behavior relies on explicit behavior in {@link #popSystemNavigator()}. It's
* not recommended to override that method when enabling this attribute, but if you do, you
* should always fall back to calling {@code super.popSystemNavigator()} when not relying on
* custom behavior.
*/
@NonNull
public CachedEngineFragmentBuilder shouldAutomaticallyHandleOnBackPressed(
boolean shouldAutomaticallyHandleOnBackPressed) {
this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed;
return this;
}
/**
* Whether to delay the Android drawing pass till after the Flutter UI has been displayed.
*
* <p>See {#link FlutterActivityAndFragmentDelegate#onCreateView} for more details.
*/
@NonNull
public CachedEngineFragmentBuilder shouldDelayFirstAndroidViewDraw(
@NonNull boolean shouldDelayFirstAndroidViewDraw) {
this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw;
return this;
}
/**
* Creates a {@link Bundle} of arguments that are assigned to the new {@code FlutterFragment}.
*
* <p>Subclasses should override this method to add new properties to the {@link Bundle}.
* Subclasses must call through to the super method to collect all existing property values.
*/
@NonNull
protected Bundle createArgs() {
Bundle args = new Bundle();
args.putString(ARG_CACHED_ENGINE_ID, engineId);
args.putBoolean(ARG_DESTROY_ENGINE_WITH_FRAGMENT, destroyEngineWithFragment);
args.putBoolean(ARG_HANDLE_DEEPLINKING, handleDeeplinking);
args.putString(
ARG_FLUTTERVIEW_RENDER_MODE,
renderMode != null ? renderMode.name() : RenderMode.surface.name());
args.putString(
ARG_FLUTTERVIEW_TRANSPARENCY_MODE,
transparencyMode != null ? transparencyMode.name() : TransparencyMode.transparent.name());
args.putBoolean(ARG_SHOULD_ATTACH_ENGINE_TO_ACTIVITY, shouldAttachEngineToActivity);
args.putBoolean(
ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, shouldAutomaticallyHandleOnBackPressed);
args.putBoolean(ARG_SHOULD_DELAY_FIRST_ANDROID_VIEW_DRAW, shouldDelayFirstAndroidViewDraw);
return args;
}
/**
* Constructs a new {@code FlutterFragment} (or a subclass) that is configured based on
* properties set on this {@code CachedEngineFragmentBuilder}.
*/
@NonNull
public <T extends FlutterFragment> T build() {
try {
@SuppressWarnings("unchecked")
T frag = (T) fragmentClass.getDeclaredConstructor().newInstance();
if (frag == null) {
throw new RuntimeException(
"The FlutterFragment subclass sent in the constructor ("
+ fragmentClass.getCanonicalName()
+ ") does not match the expected return type.");
}
Bundle args = createArgs();
frag.setArguments(args);
return frag;
} catch (Exception e) {
throw new RuntimeException(
"Could not instantiate FlutterFragment subclass (" + fragmentClass.getName() + ")", e);
}
}
}
// Delegate that runs all lifecycle and OS hook logic that is common between
// FlutterActivity and FlutterFragment. See the FlutterActivityAndFragmentDelegate
// implementation for details about why it exists.
@VisibleForTesting @Nullable /* package */ FlutterActivityAndFragmentDelegate delegate;
@NonNull private FlutterActivityAndFragmentDelegate.DelegateFactory delegateFactory = this;
/** Default delegate factory that creates a simple FlutterActivityAndFragmentDelegate instance. */
public FlutterActivityAndFragmentDelegate createDelegate(
FlutterActivityAndFragmentDelegate.Host host) {
return new FlutterActivityAndFragmentDelegate(host);
}
private final OnBackPressedCallback onBackPressedCallback =
new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
onBackPressed();
}
};
public FlutterFragment() {
// Ensure that we at least have an empty Bundle of arguments so that we don't
// need to continually check for null arguments before grabbing one.
setArguments(new Bundle());
}
/**
* This method exists so that JVM tests can ensure that a delegate exists without putting this
* Fragment through any lifecycle events, because JVM tests cannot handle executing any lifecycle
* methods, at the time of writing this.
*
* <p>The testing infrastructure should be upgraded to make FlutterFragment tests easy to write
* while exercising real lifecycle methods. At such a time, this method should be removed.
*/
// TODO(mattcarroll): remove this when tests allow for it
// (https://github.com/flutter/flutter/issues/43798)
@VisibleForTesting
/* package */ void setDelegateFactory(
@NonNull FlutterActivityAndFragmentDelegate.DelegateFactory delegateFactory) {
this.delegateFactory = delegateFactory;
delegate = delegateFactory.createDelegate(this);
}
/**
* Returns the Android App Component exclusively attached to {@link
* io.flutter.embedding.engine.FlutterEngine}.
*/
@Override
public ExclusiveAppComponent<Activity> getExclusiveAppComponent() {
return delegate;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
delegate = delegateFactory.createDelegate(this);
delegate.onAttach(context);
if (getArguments().getBoolean(ARG_SHOULD_AUTOMATICALLY_HANDLE_ON_BACK_PRESSED, false)) {
requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}
context.registerComponentCallbacks(this);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate.onRestoreInstanceState(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(
LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return delegate.onCreateView(
inflater,
container,
savedInstanceState,
/*flutterViewId=*/ FLUTTER_VIEW_ID,
shouldDelayFirstAndroidViewDraw());
}
@Override
public void onStart() {
super.onStart();
if (stillAttachedForEvent("onStart")) {
delegate.onStart();
}
}
@Override
public void onResume() {
super.onResume();
if (stillAttachedForEvent("onResume")) {
delegate.onResume();
}
}
// TODO(mattcarroll): determine why this can't be in onResume(). Comment reason, or move if
// possible.
@ActivityCallThrough
public void onPostResume() {
if (stillAttachedForEvent("onPostResume")) {
delegate.onPostResume();
}
}
@Override
public void onPause() {
super.onPause();
if (stillAttachedForEvent("onPause")) {
delegate.onPause();
}
}
@Override
public void onStop() {
super.onStop();
if (stillAttachedForEvent("onStop")) {
delegate.onStop();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (stillAttachedForEvent("onDestroyView")) {
delegate.onDestroyView();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (stillAttachedForEvent("onSaveInstanceState")) {
delegate.onSaveInstanceState(outState);
}
}
@Override
public void detachFromFlutterEngine() {
Log.w(
TAG,
"FlutterFragment "
+ this
+ " connection to the engine "
+ getFlutterEngine()
+ " evicted by another attaching activity");
if (delegate != null) {
// Redundant calls are ok.
delegate.onDestroyView();
delegate.onDetach();
}
}
@Override
public void onDetach() {
getContext().unregisterComponentCallbacks(this);
super.onDetach();
if (delegate != null) {
delegate.onDetach();
delegate.release();
delegate = null;
} else {
Log.v(TAG, "FlutterFragment " + this + " onDetach called after release.");
}
}
/**
* The result of a permission request has been received.
*
* <p>See {@link android.app.Activity#onRequestPermissionsResult(int, String[], int[])}
*
* <p>
*
* @param requestCode identifier passed with the initial permission request
* @param permissions permissions that were requested
* @param grantResults permission grants or denials
*/
@ActivityCallThrough
public void onRequestPermissionsResult(
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (stillAttachedForEvent("onRequestPermissionsResult")) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/**
* A new Intent was received by the {@link android.app.Activity} that currently owns this {@link
* Fragment}.
*
* <p>See {@link android.app.Activity#onNewIntent(Intent)}
*
* <p>
*
* @param intent new Intent
*/
@ActivityCallThrough
public void onNewIntent(@NonNull Intent intent) {
if (stillAttachedForEvent("onNewIntent")) {
delegate.onNewIntent(intent);
}
}
/**
* The hardware back button was pressed.
*
* <p>If the fragment uses {@code shouldAutomaticallyHandleOnBackPressed(true)}, this method
* should not be called through. It will be called automatically instead.
*
* <p>See {@link android.app.Activity#onBackPressed()}
*/
@ActivityCallThrough
public void onBackPressed() {
if (stillAttachedForEvent("onBackPressed")) {
delegate.onBackPressed();
}
}
/**
* A result has been returned after an invocation of {@link
* Fragment#startActivityForResult(Intent, int)}.
*
* <p>
*
* @param requestCode request code sent with {@link Fragment#startActivityForResult(Intent, int)}
* @param resultCode code representing the result of the {@code Activity} that was launched
* @param data any corresponding return data, held within an {@code Intent}
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (stillAttachedForEvent("onActivityResult")) {
delegate.onActivityResult(requestCode, resultCode, data);
}
}
/**
* The {@link android.app.Activity} that owns this {@link Fragment} is about to go to the
* background as the result of a user's choice/action, i.e., not as the result of an OS decision.
*
* <p>See {@link android.app.Activity#onUserLeaveHint()}
*/
@ActivityCallThrough
public void onUserLeaveHint() {
if (stillAttachedForEvent("onUserLeaveHint")) {
delegate.onUserLeaveHint();
}
}
/**
* Callback invoked when memory is low.
*
* <p>This implementation forwards a memory pressure warning to the running Flutter app.
*
* <p>
*
* @param level level
*/
@Override
public void onTrimMemory(int level) {
if (stillAttachedForEvent("onTrimMemory")) {
delegate.onTrimMemory(level);
}
}
/**
* {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link
* FlutterActivityAndFragmentDelegate} to obtain Flutter shell arguments when initializing