Skip to content

Commit 38e799a

Browse files
gmackallcamsim99
andauthored
[Android] Refactor Intent-driven engine flags into a variant-specific module (flutter#191924)
Configures the Android embedding to ignore engine configuration flags set via `Intent` in release mode. All flag parsing from `Intent`s is also stripped from release engine binaries as an additional security measure. Also adds an integration test to ensure flags set via `Intent` are ignored for apps running in release mode. As part of this implementation, deprecates the internal interface method `FlutterActivityAndFragmentDelegate.Host.getFlutterShellArgs` which is to be replaced by`FlutterActivityAndFragmentDelegate.Host.getFlutterEngineFlags`. After a stable release, `getFlutterShellArgs` will be removed: flutter#193256. **This is not a breaking change; developers cannot override this interface.** They can only subclass `FlutterActivity` and `FlutterFragment` and call `getFlutterShellArgs` which will still work as intended with a deprecation notice. Fixes flutter#190461. Related issue: While working on this, I thought it would be good to track adding the ability to negate all flags because currently, presence-only boolean flags (like `--trace-startup`) cannot have their setting in the manifest negated by the command line, which is counter-intuitive: flutter#193354 Related PR: Made some updates to the breaking change page for this project for flutter/website#13931 (directly related to my `Flutter-Android-Engine-Flags.md‎` updates) (@camsim99 authored description) ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [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. --------- Co-authored-by: Camille Simon <[email protected]> Co-authored-by: Camille Simon <[email protected]>
1 parent 61407e9 commit 38e799a

33 files changed

Lines changed: 1019 additions & 133 deletions

‎.ci.yaml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3212,6 +3212,15 @@ targets:
32123212
["devicelab", "linux"]
32133213
task_name: android_engine_flags_release_test
32143214

3215+
- name: Linux_android_emu android_intent_parsing_test
3216+
bringup: true
3217+
recipe: devicelab/devicelab_drone
3218+
timeout: 60
3219+
properties:
3220+
tags: >
3221+
["devicelab", "linux"]
3222+
task_name: android_intent_parsing_test
3223+
32153224
# linux mokey benchmark
32163225
- name: Linux_mokey new_gallery__crane_perf
32173226
recipe: devicelab/devicelab_drone

‎TESTOWNERS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
/dev/devicelab/bin/tasks/android_defines_test.dart @jesswrd @flutter/android
1515
/dev/devicelab/bin/tasks/android_engine_flags_debug_test.dart @camsim99 @flutter/android
1616
/dev/devicelab/bin/tasks/android_engine_flags_release_test.dart @camsim99 @flutter/android
17+
/dev/devicelab/bin/tasks/android_intent_parsing_test.dart @camsim99 @flutter/android
1718
/dev/devicelab/bin/tasks/android_intent_security_test.dart @camsim99 @flutter/android
1819
/dev/devicelab/bin/tasks/android_java11_dependency_smoke_tests.dart @jesswrd @flutter/android
1920
/dev/devicelab/bin/tasks/android_java17_build_android_host_app_with_module_aar.dart @jesswrd @flutter/android
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter_devicelab/framework/framework.dart';
6+
import 'package:flutter_devicelab/tasks/android_intent_parsing_test.dart';
7+
8+
void main() {
9+
task(createAndroidIntentParsingTest());
10+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// Copyright 2014 The Flutter Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'dart:async';
6+
7+
import 'package:path/path.dart' as path;
8+
9+
import '../framework/devices.dart';
10+
import '../framework/framework.dart';
11+
import '../framework/task_result.dart';
12+
import '../framework/utils.dart';
13+
14+
TaskFunction createAndroidIntentParsingTest() {
15+
return () async {
16+
final Device device = await devices.workingDevice;
17+
await device.unlock();
18+
final String deviceId = device.deviceId;
19+
final String testDirectory = path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ui');
20+
21+
const testPackageName = 'com.yourcompany.integration_ui';
22+
const mainActivityName = '$testPackageName/.MainActivity';
23+
24+
Future<void> testMode({required String mode, required bool expectVerbose}) async {
25+
section('--- Testing $mode mode ---');
26+
await inDirectory<void>(testDirectory, () async {
27+
await flutter('build', options: <String>['apk', '--$mode']);
28+
final String apkPath = path.join('build', 'app', 'outputs', 'flutter-apk', 'app-$mode.apk');
29+
30+
// Ensure clean state
31+
await exec('adb', <String>['-s', deviceId, 'uninstall', testPackageName], canFail: true);
32+
await exec('adb', <String>['-s', deviceId, 'install', '-r', apkPath]);
33+
await exec('adb', <String>['-s', deviceId, 'logcat', '-c']);
34+
35+
await exec('adb', <String>[
36+
'-s',
37+
deviceId,
38+
'shell',
39+
'am',
40+
'start',
41+
'-W',
42+
'-n',
43+
mainActivityName,
44+
'-a',
45+
'android.intent.action.RUN',
46+
'--ez',
47+
'verbose-logging',
48+
'true',
49+
]);
50+
51+
// The app is fully launched. Give logcat a tiny buffer to flush.
52+
await Future<void>.delayed(const Duration(seconds: 1));
53+
54+
section('--- Check logcat for verbose logs in $mode ---');
55+
final String logcat = await eval('adb', <String>['-s', deviceId, 'logcat', '-d']);
56+
final bool foundInfoLog = logcat.contains('[INFO:flutter');
57+
58+
if (expectVerbose && !foundInfoLog) {
59+
throw TaskResult.failure(
60+
'Expected [INFO:] logs to be present in $mode mode when passing verbose-logging intent, but they were not found in logcat.',
61+
);
62+
} else if (!expectVerbose && foundInfoLog) {
63+
throw TaskResult.failure(
64+
'Expected [INFO:] logs to be stripped in $mode mode, but they were found in logcat!',
65+
);
66+
}
67+
68+
if (!expectVerbose) {
69+
const expectedWarning =
70+
'Setting engine flags via Intent is not supported in release mode and will be ignored.';
71+
if (!logcat.contains(expectedWarning)) {
72+
throw TaskResult.failure(
73+
'Expected warning "$expectedWarning" to be present in $mode mode logcat, but it was not found.',
74+
);
75+
}
76+
}
77+
78+
print(
79+
'Success: $mode mode behaves as expected (expectVerbose: $expectVerbose, foundInfoLog: $foundInfoLog)',
80+
);
81+
});
82+
}
83+
84+
await testMode(mode: 'debug', expectVerbose: true);
85+
await testMode(mode: 'profile', expectVerbose: true);
86+
await testMode(mode: 'release', expectVerbose: false);
87+
88+
return TaskResult.success(null);
89+
};
90+
}

‎docs/engine/Flutter-Android-Engine-Flags.md‎

Lines changed: 137 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
# Setting Flutter Android engine flags
22

3-
You can set flags for the Flutter engine on Android in two different ways:
3+
You can set flags for the Flutter engine on Android in a few different ways:
44

55
- From the command line when launching an app with the Flutter tool
66
- Via `AndroidManifest.xml` metadata (static, per-build configuration)
7+
- Via Android `Intent` extras (for debugging purposes in debug and profile modes)
78

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.
9+
Flags available on Android may be set via the command line, manifest metadata,
10+
**and/or** `Intent` extras depending on the flag and build mode. See
11+
`src/flutter/shell/platform/android/io/flutter/embedding/engine/flags/FlutterEngineFlags.java`
12+
for the list of flags that can be set for the Android shell, and see
13+
`src/flutter/shell/common/switch_defs.h` for the list of all supported flags.
1414

1515
For flags that can be set on the command line and via the manifest,
1616
see below to determine which method to use.
@@ -28,16 +28,54 @@ Use the manifest when:
2828
`src/release/AndroidManifest.xml` (or per-flavor manifests) to tailor flags
2929
per variant.
3030

31+
See [below](#how-to-set-engine-flags-in-the-manifest) for how to set flags via the manifest.
32+
3133
Use the command line when:
3234

3335
- 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+
- You need to override a value or toggle flag that is already set in the manifest temporarily
37+
for debugging or testing purposes.
38+
39+
See [below](#how-to-set-engine-flags-from-the-command-line) for how to set flags via the command line.
40+
41+
Use Android `Intent` extras when:
42+
43+
- You want to pass flags during manual debugging or automated testing in debug and profile modes (e.g., via `adb shell am start` or programmatically from host Android code). Note that `Intent` flags are disabled in release mode for security reasons.
44+
45+
See [below](#how-to-set-engine-flags-via-android-intents) for how to set flags via `Intent`s.
3646

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.**
47+
**Note on precedence:**
48+
49+
- **Flags that take values or toggles** (e.g., `--enable-impeller=true|false` or `--trace-to-file=<path>`):
50+
Command-line values and `Intent` extras take precedence over the manifest value at runtime.
51+
- **Presence-only boolean flags** (e.g., `--enable-software-rendering`, `--trace-startup`, `--verbose-logging`):
52+
These flags enable a feature if specified in the manifest, on the command line, or via `Intent` extras.
53+
They cannot be disabled from the command line or `Intent` extras if already enabled in the manifest.
54+
If you need them enabled only for specific builds, specify them in variant-specific manifests
55+
(e.g., `src/debug/AndroidManifest.xml`). Issue [#193354](https://github.com/flutter/flutter/issues/193354)
56+
tracks adding the ability to negate flags from the command line and `Intent` extras so manifest settings can be overridden.
57+
58+
## Release-mode restrictions
59+
60+
For security purposes, release builds impose several restrictions on how engine
61+
flags can be delivered and which flags are permitted:
62+
63+
- **Intent flags are disabled in release mode:** For security purposes, the
64+
Android embedding ignores all engine flags passed via Android `Intent`
65+
extras in release builds. Setting engine flags via `Intent` is only
66+
supported in debug and profile modes. For more background on this security restriction
67+
and how to migrate, see [Restrict command-line flags on prebuilt Android release binaries](https://docs.flutter.dev/release/breaking-changes/restrict-android-engine-flags-release-mode).
68+
- **Allowed flags in release mode:** Only specific security-reviewed flags are
69+
allowed in release mode. The Android embedding enforces this policy (see
70+
`src/flutter/shell/platform/android/io/flutter/embedding/engine/flags/FlutterEngineFlags.java`,
71+
which marks allowed flags with `allowedInRelease`). Disallowed flags specified
72+
in the manifest, on the command line, or dynamically in code in release mode will be ignored.
73+
- **Prebuilt binary limitation (`--use-application-binary`):** In debug and profile modes,
74+
the Flutter tool delivers command-line flags at runtime via `Intent` extras. In release mode,
75+
command-line flags are injected into `AndroidManifest.xml` at build time. Consequently,
76+
**command-line flags cannot be passed when running a prebuilt release binary** (e.g.,
77+
`flutter run --release --use-application-binary=...`).
3978

40-
See below for details on using each method.
4179

4280
## How to set engine flags from the command line
4381

@@ -53,16 +91,19 @@ flutter run --trace-startup \
5391
Notes:
5492

5593
- Flags that take values use the `--flag=value` form (with `=`). The Flutter
56-
tool forwards them in that form to the Android embedding.
94+
tool forwards them in that form to the Android embedding.
95+
- **Limitation with `--use-application-binary`:** Release builds rely on build-time
96+
manifest injection of command-line flags and ignore runtime `Intent` extras. Consequently,
97+
command-line flags cannot be passed when running a prebuilt release binary. See
98+
[Release-mode restrictions](#release-mode-restrictions) for details.
5799

58100
## How to set engine flags in the manifest
59101

60102
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
103+
`io.flutter.embedding.android.` and are suffixed with the metadata name for the
104+
related command-line flag as defined in
105+
`src/flutter/shell/platform/android/io/flutter/embedding/engine/flags/FlutterEngineFlags.java`.
106+
For example, the `--impeller-lazy-shader-mode=` command-line flag corresponds to the metadata key
66107
`io.flutter.embedding.android.ImpellerLazyShaderInitialization`.
67108

68109
For flags that take values, set the numeric, string, or boolean value (without
@@ -90,38 +131,89 @@ Set the `--enable-flutter-gpu` flag:
90131
```xml
91132
<meta-data
92133
android:name="io.flutter.embedding.android.EnableFlutterGPU"
93-
android:value=true
94-
/>
134+
android:value="true" />
95135
```
96136

97137
For flags that take boolean values, you must explicitly set
98138
`android:value="true"` to enable the flag. Omitting the value or
99139
providing a non-boolean value (e.g., a typo like `"Fasle"`) will
100140
default to `false` (disabled).
101141

102-
## Release-mode restrictions
142+
## How to set engine flags via Android Intents
103143

104-
- Some flags are not allowed in release mode. The Android embedding enforces
105-
this policy (see `src/flutter/shell/platform/android/io/flutter/
106-
embedding/engine/FlutterEngineFlags`, which marks allowed flags
107-
with `allowedInRelease`). If a disallowed flag is set in release, it will
108-
be ignored.
109-
- If you need different behavior in release vs debug/profile mode, configure it
110-
via variant-specific manifests or product flavors.
144+
During development, in debug and profile modes, engine flags can also be passed
145+
directly to a `FlutterActivity` via Android `Intent` extras. This is useful for
146+
quick debugging workflows, automated device tests, or when launching an activity
147+
directly via `adb`:
111148

112-
## How to set engine flags dynamically
149+
```bash
150+
adb shell am start -n com.example.myapp/.MainActivity \
151+
--ez trace-startup true \
152+
--es trace-to-file /data/local/tmp/trace.json
153+
```
113154

114-
As of the writing of this document, setting Flutter shell arguments via an
115-
Android `Intent` is no longer supported. If you need per-launch or
116-
runtime-controlled flags in an add-to-app integration, you may do so
117-
programatically before engine initialization.
155+
Or programmatically when launching an `Intent` from native Android code:
118156

119-
To do that, supply engine arguments directly to a `FlutterEngine` with the
120-
desired flags from the earliest point you can control in your
121-
application. For example, if you are writing an add-to-app app that launches
122-
a `FlutterActivity` or `FlutterFragment`, then you can cache a
123-
`FlutterEngine` that is initialized with your desired
124-
engine flags:
157+
```kotlin
158+
val intent = Intent(context, MainActivity::class.java).apply {
159+
putExtra("trace-startup", true)
160+
putExtra("enable-software-rendering", true)
161+
}
162+
startActivity(intent)
163+
```
164+
165+
The `Intent` extra key corresponds to the command-line flag name without the leading `--`
166+
(for example, `trace-startup`, `trace-to-file`, `enable-software-rendering`, `enable-impeller`,
167+
or `dart-flags`). Both boolean flags and flags that take string/integer values are supported.
168+
169+
Notes:
170+
171+
- **Intent flags are disabled in release mode:** As described in
172+
[Release-mode restrictions](#release-mode-restrictions), the Android embedding
173+
ignores all engine flags passed via Android `Intent` extras in release builds.
174+
175+
### How to alternatively set engine flags dynamically
176+
177+
As stated above, setting Flutter shell arguments via an Android `Intent` is not
178+
supported in release mode. If you need per-launch or runtime-controlled flags in an
179+
add-to-app integration or custom activity, you can provide them programmatically
180+
before engine initialization.
181+
182+
> [!NOTE]
183+
> Even when setting flags dynamically in code, release builds enforce the same
184+
> security policy: any flags not marked `allowedInRelease` in
185+
> `FlutterEngineFlags.java` will be ignored by `FlutterLoader` (see
186+
> [Release-mode restrictions](#release-mode-restrictions)).
187+
188+
### Option 1: Overriding `getFlutterEngineFlags` in `FlutterActivity` or `FlutterFragment`
189+
190+
If you subclass `FlutterActivity` or `FlutterFragment`, you can override
191+
`getFlutterEngineFlags()` to supply custom flags directly without manually
192+
managing the engine lifecycle:
193+
194+
```kotlin
195+
class MyFlutterActivity : FlutterActivity() {
196+
override fun getFlutterEngineFlags(): List<String> {
197+
val flags = super.getFlutterEngineFlags().toMutableList()
198+
flags.add("--trace-startup")
199+
return flags
200+
}
201+
}
202+
```
203+
204+
For `FlutterFragment`, you can also configure flags using `NewEngineFragmentBuilder`:
205+
206+
```kotlin
207+
val fragment = FlutterFragment.NewEngineFragmentBuilder()
208+
.flutterEngineFlags(listOf("--trace-startup"))
209+
.build<FlutterFragment>()
210+
```
211+
212+
### Option 2: Pre-initializing and caching a `FlutterEngine`
213+
214+
If you need full control over the engine lifecycle (such as in an add-to-app host application),
215+
supply engine arguments directly to a `FlutterEngine` constructor from the earliest point you can
216+
control in your application:
125217

126218
```kotlin
127219
// Your native Android application
@@ -131,14 +223,13 @@ class MyApp : Application() {
131223
// Initialize the Flutter engine with desired flags
132224
val args = arrayOf(
133225
"--trace-startup",
134-
"--trace-to-file=some_file.txt",
135-
"--enable-software-rendering"
226+
"--enable-impeller=true"
136227
)
137228
val flutterEngine = FlutterEngine(this, args)
138229

139230
// Start executing Dart code in the FlutterEngine
140231
flutterEngine.dartExecutor.executeDartEntrypoint(
141-
DartEntrypoint.createDefault()
232+
DartExecutor.DartEntrypoint.createDefault()
142233
)
143234

144235
// Store the engine in the cache for later use
@@ -163,10 +254,8 @@ supportFragmentManager
163254
.commit()
164255
```
165256

166-
For a normal Flutter Android app, you can create and initialize a `FlutterEngine`
167-
with your desired flags the same as in the example above, then override
168-
`provideFlutterEngine` in your app's `FlutterActivity` to provide the
169-
configured `FlutterEngine`. For example:
257+
Alternatively, for a standalone Flutter Android app, you can create and initialize a `FlutterEngine`
258+
as above, and override `provideFlutterEngine` in your `FlutterActivity`:
170259

171260
```kotlin
172261
// Your Flutter Android application
@@ -176,8 +265,7 @@ class MyApplication : FlutterApplication() {
176265

177266
val args = arrayOf(
178267
"--trace-startup",
179-
"--trace-to-file=some_file.txt",
180-
"--enable-software-rendering"
268+
"--enable-impeller=true"
181269
)
182270
val flutterEngine = FlutterEngine(this, args)
183271
flutterEngine.dartExecutor.executeDartEntrypoint(
@@ -190,7 +278,7 @@ class MyApplication : FlutterApplication() {
190278
}
191279

192280
// Your Flutter Android Activity
193-
class MainActivity: FlutterActivity() {
281+
class MainActivity : FlutterActivity() {
194282
override fun provideFlutterEngine(context: Context): FlutterEngine? {
195283
return FlutterEngineCache
196284
.getInstance()

0 commit comments

Comments
 (0)