Skip to content

Commit 994b73f

Browse files
Reland "[Android] Add mechanism for setting Android engine flags via Android manifest (take 2)" (#182522)
### Overview Re-lands #181632 which TLDR does the following: **Same old same old changes from original PR** - Refactors all engine flags recognized by the Flutter Android embedding (specifically those previously recognized by [`FlutterShellArgs`](https://github.com/flutter/flutter/blob/4f5478cce38d837e14b7a032a12500d3fc0f1310/engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterShellArgs.java) and all of those used to initialize the engine in `FlutterLoader`) into a new class `FlutterEngineFlags` (`FlutterShellArgs` is kept for now to maintain backwards compatibility; see #182153 for details) - Adds the ability to set engine flags (that are recognized by `FlutterEngineFlags`) via the manifest - Adds warnings for developers that set engine flags via `Intent`s as this will be disabled as part of #180686. - Disallows debug/test only flags in release mode **New changes/fixes** > [!NOTE] > This re-land was required because when previously submitted, it caused b/483299339. I have confirmed that this bug has been fixed in this PR; see go/flutter-android-setting-flags-in-manifest-perf-comparison for A/B test results with the previous version of this PR (#181632) and commit d6d4a07 of this PR. - [Critical change] To fix the bug caught by b/483299339, `--merged-platform-ui-thread` flag is added to `FlutterEngineFlag`s - [Behavior change, not critical] To avoid more bugs like b/483299339, `FlutterLoader` allows unrecognized flags specified by the command line or `Intent` extras to be used to initialize the engine for now (same behavior as before my original change but I plan to secure this in the future; see #182557) - [Small refactor] To speed up manifest argument processing time, `FlutterLoader` loops through all recognized `FlutterEngineFlag`s to check if they are present in an application's manifest versus looping through all metadata in an application's manifest and looking for recognized `FlutterEngineFlag`s (small improvement for apps with large manifests) - [Small refactor] To speed up command line argument processing time, `FlutterLoader` processes the `--aot-shared-library-name` flag in the same loop as the other flags, reducing the number of loops `ensureInitializationComplete` has to do (minimal improvement perf-wise but kept it in because it's more readable to me) ### Full description (Mostly copied from #181632) > [!NOTE] > This PR is based on conversation & feedback on go/flutter-android-harden-engine-shell-arguments. Adds a mechanism for setting Android engine flags via the manifest. If a flag is specified on the command line and in manifest metadata, the value specified on the command line will take precedence. Documentation is added on this mechanism Additionally, this PR removes the exposure of`--cache-sksl` command line flag as per [https://github.com/flutter/flutter/issues/140310#issuecomment-2708459007](https://www.google.com/url?q=https://github.com/flutter/flutter/issues/140310%23issuecomment-2708459007&sa=D&source=docs&ust=1761156167162464&usg=AOvVaw3a8ubXTtv3apknY2-P9dKe). Additionally, this PR adds documentation for the only two supported ways of setting engine flags moving forward -- via the command line or manifest. The `Intent` mechanism will be removed when #180686 is completed (intended to be a follow up to this PR). As the unit tests in this PR only cover setting flags via manifest in debug mode, I will follow up this PR with an integration test to test that flags are appropriately respected/ignored in release mode. See #178383 for my currently working but WIP draft. Part of #172553. # Follow up work: - [ ] **Migrate flags all un-migrated flags `FlutterEngineFlags`** #182852 - [ ] **Add integration test for this new added mechanism.** This will land as an immediate follow-up to this PR. WIP in #182241. - [ ] **Remove support for setting shell arguments via `Intent`.** This task will be a follow up to this work + the integration test landing, and will complete work for #172553. See #180686 for details. - [ ] **Only allow known engine flags to be passed to the engine.** This is more of a P2 but would be a nice additional security feature; see #182557. ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
1 parent 483cce9 commit 994b73f

18 files changed

Lines changed: 2016 additions & 294 deletions
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
# Setting Flutter Android engine flags
2+
3+
You can set flags for the Flutter engine on Android in two different ways:
4+
5+
- From the command line when launching an app with the Flutter tool
6+
- Via `AndroidManifest.xml` metadata (static, per-build configuration)
7+
8+
Flags available on Android may be set via the command line **and/or** via
9+
manifest metadata depending on the flag. See
10+
`src/flutter/shell/platform/android/io/flutter/embedding/engine/`
11+
`FlutterEngineFlags.java` for the list of flags that can be set for
12+
the Android shell, and see `src/flutter/shell/common/switch_defs.h`
13+
for the list of all supported flags.
14+
15+
For flags that can be set on the command line and via the manifest,
16+
see below to determine which method to use.
17+
18+
## When to use manifest metadata versus the command line
19+
20+
Use the manifest when:
21+
22+
- You want a fixed, reproducible baseline of engine flags
23+
for your app across all launches. This is ideal for CI and for enforcing a
24+
consistent configuration for your app.
25+
- You want to vary flags by build mode or product flavor
26+
via manifest merging. For example, place metadata in
27+
`src/debug/AndroidManifest.xml`, `src/profile/AndroidManifest.xml`, and
28+
`src/release/AndroidManifest.xml` (or per-flavor manifests) to tailor flags
29+
per variant.
30+
31+
Use the command line when:
32+
33+
- You want to quickly experiment with a flag for a single run of your app.
34+
- You need to override a flag that is already set in the manifest temporarily for debugging
35+
or testing purposes.
36+
37+
**Note: If a flag is specified both on the command line and in the manifest,
38+
the command-line value takes precedence at runtime.**
39+
40+
See below for details on using each method.
41+
42+
## How to set engine flags from the command line
43+
44+
When you run a standalone Flutter app with the Flutter tool, engine flags
45+
can be passed directly and are forwarded to the Android engine. Examples:
46+
47+
```bash
48+
flutter run --trace-startup \
49+
--enable-software-rendering \
50+
--dart-flags="--enable-asserts"
51+
```
52+
53+
Notes:
54+
55+
- Flags that take values use the `--flag=value` form (with `=`). The Flutter
56+
tool forwards them in that form to the Android embedding.
57+
58+
## How to set engine flags in the manifest
59+
60+
All manifest metadata keys must be prefixed with the package name
61+
`io.flutter.embedding.android` and are suffixed with the metadata name for the
62+
related command line flag as determined in
63+
`src/flutter/shell/platform/android/io/flutter/embedding/engine/`
64+
`FlutterEngineFlags.java`. For example, the `--impeller-lazy-shader-mode=`
65+
command line flag corresponds to the metadata key
66+
`io.flutter.embedding.android.ImpellerLazyShaderInitialization`.
67+
68+
For flags that take values, set the numeric, string, or boolean value (without
69+
the leading `--flag=` prefix).
70+
71+
### Examples
72+
73+
Set the `--trace-to-file=` flag to `some_file.txt`:
74+
75+
```xml
76+
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
77+
package="com.example.myapp">
78+
<application ...>
79+
<meta-data
80+
android:name="io.flutter.embedding.android.TraceToFile"
81+
android:value="some_file.txt"/>
82+
...
83+
</application>
84+
</manifest>
85+
```
86+
87+
Set the `--enable-flutter-gpu` flag:
88+
89+
```xml
90+
<meta-data
91+
android:name="io.flutter.embedding.android.EnableFlutterGPU"
92+
android:value=true
93+
/>
94+
```
95+
96+
For flags that take boolean values, if you omit a value entirely, it
97+
will be assumed to be true. For example, this is the same as the
98+
example above:
99+
100+
```xml
101+
<meta-data
102+
android:name="io.flutter.embedding.android.EnableFlutterGPU"
103+
/>
104+
```
105+
106+
## Release-mode restrictions
107+
108+
- Some flags are not allowed in release mode. The Android embedding enforces
109+
this policy (see `src/flutter/shell/platform/android/io/flutter/
110+
embedding/engine/FlutterEngineFlags`, which marks allowed flags
111+
with `allowedInRelease`). If a disallowed flag is set in release, it will
112+
be ignored.
113+
- If you need different behavior in release vs debug/profile mode, configure it
114+
via variant-specific manifests or product flavors.
115+
116+
## How to set engine flags dynamically
117+
118+
As of the writing of this document, setting Flutter shell arguments via an
119+
Android `Intent` is no longer supported. If you need per-launch or
120+
runtime-controlled flags in an add-to-app integration, you may do so
121+
programatically before engine initialization.
122+
123+
To do that, supply engine arguments directly to a `FlutterEngine` with the
124+
desired flags from the earliest point you can control in your
125+
application. For example, if you are writing an add-to-app app that launches
126+
a `FlutterActivity` or `FlutterFragment`, then you can cache a
127+
`FlutterEngine` that is initialized with your desired
128+
engine flags:
129+
130+
```kotlin
131+
// Your native Android application
132+
class MyApp : Application() {
133+
override fun onCreate() {
134+
super.onCreate()
135+
// Initialize the Flutter engine with desired flags
136+
val args = arrayOf(
137+
"--trace-startup",
138+
"--trace-to-file=some_file.txt",
139+
"--enable-software-rendering"
140+
)
141+
val flutterEngine = FlutterEngine(this, args)
142+
143+
// Start executing Dart code in the FlutterEngine
144+
flutterEngine.dartExecutor.executeDartEntrypoint(
145+
DartEntrypoint.createDefault()
146+
)
147+
148+
// Store the engine in the cache for later use
149+
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine)
150+
}
151+
}
152+
```
153+
154+
Then, your `Activity` can launch a `FlutterActivity` or `FlutterFragment`
155+
with that cached `FlutterEngine`:
156+
157+
```kotlin
158+
// Start a FlutterActivity using the cached engine...
159+
val intent = FlutterActivity.withCachedEngine("my_engine_id").build(this)
160+
startActivity(intent)
161+
162+
// Or launch a FlutterFragment using the cached engine
163+
val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id").build()
164+
supportFragmentManager
165+
.beginTransaction()
166+
.add(R.id.fragment_container, flutterFragment, TAG_FLUTTER_FRAGMENT)
167+
.commit()
168+
```
169+
170+
For a normal Flutter Android app, you can create and initialize a `FlutterEngine`
171+
with your desired flags the same as in the example above, then override
172+
`provideFlutterEngine` in your app's `FlutterActivity` to provide the
173+
configured `FlutterEngine`. For example:
174+
175+
```kotlin
176+
// Your Flutter Android application
177+
class MyApplication : FlutterApplication() {
178+
override fun onCreate() {
179+
super.onCreate()
180+
181+
val args = arrayOf(
182+
"--trace-startup",
183+
"--trace-to-file=some_file.txt",
184+
"--enable-software-rendering"
185+
)
186+
val flutterEngine = FlutterEngine(this, args)
187+
flutterEngine.dartExecutor.executeDartEntrypoint(
188+
DartExecutor.DartEntrypoint.createDefault()
189+
)
190+
FlutterEngineCache
191+
.getInstance()
192+
.put(MY_ENGINE_ID, flutterEngine)
193+
}
194+
}
195+
196+
// Your Flutter Android Activity
197+
class MainActivity: FlutterActivity() {
198+
override fun provideFlutterEngine(context: Context): FlutterEngine? {
199+
return FlutterEngineCache
200+
.getInstance()
201+
.get(MyApplication.MY_ENGINE_ID)
202+
}
203+
}
204+
```

‎engine/src/flutter/shell/platform/android/BUILD.gn‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ android_java_sources = [
250250
"io/flutter/embedding/engine/FlutterEngine.java",
251251
"io/flutter/embedding/engine/FlutterEngineCache.java",
252252
"io/flutter/embedding/engine/FlutterEngineConnectionRegistry.java",
253+
"io/flutter/embedding/engine/FlutterEngineFlags.java",
253254
"io/flutter/embedding/engine/FlutterEngineGroup.java",
254255
"io/flutter/embedding/engine/FlutterEngineGroupCache.java",
255256
"io/flutter/embedding/engine/FlutterJNI.java",

‎engine/src/flutter/shell/platform/android/io/flutter/embedding/android/FlutterActivityAndFragmentDelegate.java‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import io.flutter.Log;
3030
import io.flutter.embedding.engine.FlutterEngine;
3131
import io.flutter.embedding.engine.FlutterEngineCache;
32+
import io.flutter.embedding.engine.FlutterEngineFlags;
3233
import io.flutter.embedding.engine.FlutterEngineGroup;
3334
import io.flutter.embedding.engine.FlutterEngineGroupCache;
3435
import io.flutter.embedding.engine.FlutterShellArgs;
@@ -38,6 +39,7 @@
3839
import io.flutter.plugin.view.SensitiveContentPlugin;
3940
import java.util.Arrays;
4041
import java.util.List;
42+
import java.util.Set;
4143

4244
/**
4345
* Delegate that implements all Flutter logic that is the same between a {@link FlutterActivity} and
@@ -331,6 +333,7 @@ private FlutterEngineGroup.Options addEntrypointOptions(FlutterEngineGroup.Optio
331333
"No preferred FlutterEngine was provided. Creating a new FlutterEngine for"
332334
+ " this FlutterFragment.");
333335

336+
warnIfEngineFlagsSetViaIntent(host.getActivity().getIntent());
334337
FlutterEngineGroup group =
335338
engineGroup == null
336339
? new FlutterEngineGroup(host.getContext(), host.getFlutterShellArgs().toArray())
@@ -344,6 +347,32 @@ private FlutterEngineGroup.Options addEntrypointOptions(FlutterEngineGroup.Optio
344347
isFlutterEngineFromHost = false;
345348
}
346349

350+
// As part of https://github.com/flutter/flutter/issues/180686, the ability
351+
// to set engine flags via Intent extras will be removed, so warn
352+
// developers that engine shell arguments set that way will be ignored.
353+
private void warnIfEngineFlagsSetViaIntent(@NonNull Intent intent) {
354+
if (intent.getExtras() == null) {
355+
return;
356+
}
357+
358+
Bundle extras = intent.getExtras();
359+
Set<String> extrasKeys = extras.keySet();
360+
361+
for (String extrasKey : extrasKeys) {
362+
FlutterEngineFlags.Flag flag = FlutterEngineFlags.getFlagFromIntentKey(extrasKey);
363+
if (flag != null) {
364+
Log.i(
365+
TAG,
366+
"If you are attempting to set "
367+
+ flag.engineArgument
368+
+ " via Intent extras to launch a Flutter component outside of using the Flutter CLI, note that support for setting engine flags on Android via Intent will soon be dropped; see https://github.com/flutter/flutter/issues/180686 for more information on this breaking change. To migrate, set "
369+
+ flag.engineArgument
370+
+ " or any other flags specified via Intent extras on the command line instead or see https://github.com/flutter/flutter/blob/main/docs/engine/Flutter-Android-Engine-Flags.md for alternative methods.");
371+
break;
372+
}
373+
}
374+
}
375+
347376
/**
348377
* Invoke this method from {@code Activity#onCreate(Bundle)} to create the content {@code View},
349378
* or from {@code Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}.

‎engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterEngine.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,8 @@ public void onEngineWillDestroy() {
177177
* native library and start a Dart VM.
178178
*
179179
* <p>In order to pass Dart VM initialization arguments (see {@link
180-
* io.flutter.embedding.engine.FlutterShellArgs}) when creating the VM, manually set the
181-
* initialization arguments by calling {@link
180+
* io.flutter.embedding.engine.FlutterEngineFlags} for all available flags) when creating the VM,
181+
* manually set the initialization arguments by calling {@link
182182
* io.flutter.embedding.engine.loader.FlutterLoader#startInitialization(Context)} and {@link
183183
* io.flutter.embedding.engine.loader.FlutterLoader#ensureInitializationComplete(Context,
184184
* String[])} before constructing the engine.

‎engine/src/flutter/shell/platform/android/io/flutter/embedding/engine/FlutterEngineConnectionRegistry.java‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959

6060
// Standard FlutterPlugin
6161
@NonNull private final FlutterEngine flutterEngine;
62+
@NonNull private final FlutterLoader flutterLoader;
6263
@NonNull private final FlutterPlugin.FlutterPluginBinding pluginBinding;
6364

6465
// ActivityAware
@@ -100,6 +101,7 @@
100101
@NonNull FlutterLoader flutterLoader,
101102
@Nullable FlutterEngineGroup group) {
102103
this.flutterEngine = flutterEngine;
104+
this.flutterLoader = flutterLoader;
103105
pluginBinding =
104106
new FlutterPlugin.FlutterPluginBinding(
105107
appContext,
@@ -326,13 +328,31 @@ public void attachToActivity(
326328

327329
private void attachToActivityInternal(@NonNull Activity activity, @NonNull Lifecycle lifecycle) {
328330
this.activityPluginBinding = new FlutterEngineActivityPluginBinding(activity, lifecycle);
331+
final Intent intent = activity.getIntent();
329332

330-
final boolean useSoftwareRendering =
331-
activity.getIntent() != null
332-
? activity
333-
.getIntent()
334-
.getBooleanExtra(FlutterShellArgs.ARG_KEY_ENABLE_SOFTWARE_RENDERING, false)
333+
// TODO(camsim99): Remove ability to set this flag via Intents. See
334+
// https://github.com/flutter/flutter/issues/180686.
335+
boolean useSoftwareRendering =
336+
intent != null
337+
? intent.getBooleanExtra(FlutterShellArgs.ARG_KEY_ENABLE_SOFTWARE_RENDERING, false)
335338
: false;
339+
340+
// As part of https://github.com/flutter/flutter/issues/172553, the ability to set
341+
// --enable-software-rendering via Intent will be removed. Inform
342+
// developers about the new method for doing so if this was attempted.
343+
// TODO(camsim99): Remove this warning after a stable release has passed:
344+
// https://github.com/flutter/flutter/issues/179274.
345+
if (useSoftwareRendering) {
346+
Log.i(
347+
TAG,
348+
"If you are attempting to set --enable-software-rendering via Intent extras to launch a Flutter component outside of using the Flutter CLI, note that support for setting engine flags on Android via Intent will soon be dropped; see https://github.com/flutter/flutter/issues/172553 for more information on this breaking change. To migrate, set the "
349+
+ FlutterEngineFlags.ENABLE_SOFTWARE_RENDERING.metadataKey
350+
+ " metadata in the application manifest. See https://github.com/flutter/flutter/blob/main/docs/engine/Flutter-Android-Engine-Flags.md for more info.");
351+
} else {
352+
// Check manifest for software rendering configuration.
353+
useSoftwareRendering = flutterLoader.getSofwareRenderingEnabledViaManifest();
354+
}
355+
336356
flutterEngine.getPlatformViewsController().setSoftwareRendering(useSoftwareRendering);
337357

338358
// Activate the PlatformViewsController. This must happen before any plugins attempt

0 commit comments

Comments
 (0)