Unverified Commit 6a6874ec authored by Zachary Anderson's avatar Zachary Anderson Committed by GitHub

Update Android minSdkVersion to 21 (#142267)

This PR increases Android's `minSdkVersion` to 21.

There are two changes in this PR aside from simply increasing the number
from 19 to 21 everywhere.

First, tests using `flutter_gallery` fail without updating the
lockfiles. The changes in the PR are the results of running
`dev/tools/bin/generate_gradle_lockfiles.dart` on that app.

Second, from
[here](https://developer.android.com/build/multidex#mdex-pre-l):
> if your minSdkVersion is 21 or higher, multidex is enabled by default
and you don't need the multidex library.

As a result, the `multidex` option everywhere is obsolete. This PR
removes all logic and tests related to that option that I could find.
`Google testing` and `customer_tests` pass on this PR, so it seems like
this won't be too breaking if it is at all. If needed I'll give this
some time to bake in the framework before landing the flutter/engine
PRs.

Context: https://github.com/flutter/flutter/issues/138117,
https://github.com/flutter/flutter/issues/141277, b/319373605
parent bdb71b8f
......@@ -19,8 +19,8 @@ FLUTTER_ROOT="$(dirname "$(dirname "$(dirname "${BASH_SOURCE[0]}")")")"
DART_SDK_PATH="$FLUTTER_ROOT/bin/cache/dart-sdk"
DART_SDK_PATH_OLD="$DART_SDK_PATH.old"
ENGINE_STAMP="$FLUTTER_ROOT/bin/cache/engine-dart-sdk.stamp"
ENGINE_VERSION=`cat "$FLUTTER_ROOT/bin/internal/engine.version"`
ENGINE_REALM=`cat "$FLUTTER_ROOT/bin/internal/engine.realm"`
ENGINE_VERSION=$(cat "$FLUTTER_ROOT/bin/internal/engine.version")
ENGINE_REALM=$(cat "$FLUTTER_ROOT/bin/internal/engine.realm" | tr -d '[:space:]')
OS="$(uname -s)"
if [ ! -f "$ENGINE_STAMP" ] || [ "$ENGINE_VERSION" != `cat "$ENGINE_STAMP"` ]; then
......
......@@ -14,7 +14,7 @@ android {
defaultConfig {
applicationId "io.flutter.add2app"
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
......
......@@ -14,7 +14,7 @@ android {
defaultConfig {
applicationId "io.flutter.add2app"
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
......
......@@ -34,7 +34,7 @@ android {
}
defaultConfig {
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 33
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
......
......@@ -14,7 +14,7 @@ android {
defaultConfig {
applicationId "io.flutter.addtoapp"
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
......
......@@ -52,7 +52,6 @@ android {
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
buildTypes {
......@@ -68,8 +67,6 @@ flutter {
}
dependencies {
def multidex_version = "2.0.1"
implementation "androidx.multidex:multidex:$multidex_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.2.0'
implementation 'com.google.android.material:material:1.5.0'
......
......@@ -5,7 +5,6 @@ found in the LICENSE file. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="@string/app_name"
android:name="androidx.multidex.MultiDexApplication"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
......
io/flutter/app/FlutterApplication.class
io/flutter/app/FlutterMultiDexApplication.class
io/flutter/embedding/engine/loader/FlutterLoader.class
io/flutter/view/FlutterMain.class
io/flutter/util/PathUtils.class
......@@ -45,7 +45,7 @@ class FlutterExtension {
public final int compileSdkVersion = 34
/** Sets the minSdkVersion used by default in Flutter app projects. */
public final int minSdkVersion = 19
public final int minSdkVersion = 21
/**
* Sets the targetSdkVersion used by default in Flutter app projects.
......@@ -323,22 +323,6 @@ class FlutterPlugin implements Plugin<Project> {
String flutterExecutableName = Os.isFamily(Os.FAMILY_WINDOWS) ? "flutter.bat" : "flutter"
flutterExecutable = Paths.get(flutterRoot.absolutePath, "bin", flutterExecutableName).toFile()
final String propMultidexEnabled = "multidex-enabled"
if (project.hasProperty(propMultidexEnabled) &&
project.property(propMultidexEnabled).toBoolean()) {
String flutterMultidexKeepfile = Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools",
"gradle", "flutter_multidex_keepfile.txt")
project.android {
buildTypes {
release {
multiDexKeepFile(project.file(flutterMultidexKeepfile))
}
}
}
project.dependencies {
implementation("androidx.multidex:multidex:2.0.1")
}
}
// Use Kotlin DSL to handle baseApplicationName logic due to Groovy dynamic dispatch bug.
project.apply from: Paths.get(flutterRoot.absolutePath, "packages", "flutter_tools", "gradle", "src", "main", "kotlin", "flutter.gradle.kts")
......
......@@ -10,21 +10,13 @@ class FlutterPluginKts : Plugin<Project> {
project.withGroovyBuilder {
getProperty("android").withGroovyBuilder {
getProperty("defaultConfig").withGroovyBuilder {
if (project.hasProperty("multidex-enabled") &&
project.property("multidex-enabled").toString().toBoolean()) {
setProperty("multiDexEnabled", true)
getProperty("manifestPlaceholders").withGroovyBuilder {
setProperty("applicationName", "io.flutter.app.FlutterMultiDexApplication")
}
} else {
var baseApplicationName: String = "android.app.Application"
if (project.hasProperty("base-application-name")) {
baseApplicationName = project.property("base-application-name").toString()
}
// Setting to android.app.Application is the same as omitting the attribute.
getProperty("manifestPlaceholders").withGroovyBuilder {
setProperty("applicationName", baseApplicationName)
}
var baseApplicationName: String = "android.app.Application"
if (project.hasProperty("base-application-name")) {
baseApplicationName = project.property("base-application-name").toString()
}
// Setting to android.app.Application is the same as omitting the attribute.
getProperty("manifestPlaceholders").withGroovyBuilder {
setProperty("applicationName", baseApplicationName)
}
}
}
......
......@@ -587,7 +587,6 @@ class AndroidDevice extends Device {
debuggingOptions.buildInfo,
targetArchs: <AndroidArch>[androidArch],
fastStart: debuggingOptions.fastStart,
multidexEnabled: (platformArgs['multidex'] as bool?) ?? false,
),
);
// Package has been built, so we can get the updated application ID and
......
......@@ -38,7 +38,6 @@ import 'java.dart';
import 'migrations/android_studio_java_gradle_conflict_migration.dart';
import 'migrations/min_sdk_version_migration.dart';
import 'migrations/top_level_gradle_build_file_migration.dart';
import 'multidex.dart';
/// The regex to grab variant names from printBuildVariants gradle task
///
......@@ -395,16 +394,6 @@ class AndroidGradleBuilder implements AndroidBuilder {
command.add('-Ptarget-platform=$targetPlatforms');
}
command.add('-Ptarget=$target');
// Only attempt adding multidex support if all the flutter generated files exist.
// If the files do not exist and it was unintentional, the app will fail to build
// and prompt the developer if they wish Flutter to add the files again via gradle_error.dart.
if (androidBuildInfo.multidexEnabled &&
multiDexApplicationExists(project.directory) &&
androidManifestHasNameVariable(project.directory)) {
command.add('-Pmultidex-enabled=true');
ensureMultiDexApplicationExists(project.directory);
_logger.printStatus('Building with Flutter multidex support enabled.');
}
// If using v1 embedding, we want to use FlutterApplication as the base app.
final String baseApplicationName =
project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ?
......@@ -512,7 +501,6 @@ class AndroidGradleBuilder implements AndroidBuilder {
line: detectedGradleErrorLine!,
project: project,
usesAndroidX: usesAndroidX,
multidexEnabled: androidBuildInfo.multidexEnabled,
);
if (maxRetries == null || retry < maxRetries) {
......
......@@ -40,7 +40,7 @@ const String templateKotlinGradlePluginVersion = '1.7.10';
//
// Please see the README before changing any of these values.
const String compileSdkVersion = '34';
const String minSdkVersion = '19';
const String minSdkVersion = '21';
const String targetSdkVersion = '33';
const String ndkVersion = '23.1.7779620';
......@@ -107,9 +107,11 @@ final RegExp gradleOrgVersionMatch =
);
// This matches uncommented minSdkVersion lines in the module-level build.gradle
// file which have minSdkVersion 16,17, or 18 (the Jelly Bean api levels).
final RegExp jellyBeanMinSdkVersionMatch =
RegExp(r'(?<=^\s*)minSdkVersion 1[678](?=\s*(?://|$))', multiLine: true);
// file which have minSdkVersion 16,17, 18, 19, or 20.
final RegExp tooOldMinSdkVersionMatch = RegExp(
r'(?<=^\s*)minSdkVersion (1[6789]|20)(?=\s*(?://|$))',
multiLine: true,
);
// From https://docs.gradle.org/current/userguide/command_line_interface.html#command_line_interface
const String gradleVersionFlag = r'--version';
......
......@@ -42,6 +42,8 @@ class MinSdkVersionMigration extends ProjectMigrator {
@override
String migrateFileContents(String fileContents) {
return fileContents.replaceAll(jellyBeanMinSdkVersionMatch, replacementMinSdkText);
return fileContents.replaceAll(
tooOldMinSdkVersionMatch, replacementMinSdkText,
);
}
}
// Copyright 2014 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.
import 'package:xml/xml.dart';
import '../base/file_system.dart';
// These utility methods are used to generate the code for multidex support as
// well as verifying the project is properly set up.
File _getMultiDexApplicationFile(Directory projectDir) {
return projectDir.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childDirectory('java')
.childDirectory('io')
.childDirectory('flutter')
.childDirectory('app')
.childFile('FlutterMultiDexApplication.java');
}
/// Creates the FlutterMultiDexApplication.java if it does not exist.
void ensureMultiDexApplicationExists(final Directory projectDir) {
final File applicationFile = _getMultiDexApplicationFile(projectDir);
if (applicationFile.existsSync()) {
// This checks for instances of legacy versions of this file. Legacy versions maintained
// compatibility with v1 embedding by extending FlutterApplication. If we detect this,
// we replace the file with the modern v2 embedding version.
if (applicationFile.readAsStringSync().contains('android.app.Application;')) {
return;
}
}
applicationFile.createSync(recursive: true);
final StringBuffer buffer = StringBuffer();
buffer.write('''
// Generated file.
//
// If you wish to remove Flutter's multidex support, delete this entire file.
//
// Modifications to this file should be done in a copy under a different name
// as this file may be regenerated.
package io.flutter.app;
import android.app.Application;
import android.content.Context;
import androidx.annotation.CallSuper;
import androidx.multidex.MultiDex;
/**
* Extension of {@link android.app.Application}, adding multidex support.
*/
public class FlutterMultiDexApplication extends Application {
@Override
@CallSuper
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
''');
applicationFile.writeAsStringSync(buffer.toString(), flush: true);
}
/// Returns true if FlutterMultiDexApplication.java exists.
///
/// This function does not verify the contents of the file.
bool multiDexApplicationExists(final Directory projectDir) {
if (_getMultiDexApplicationFile(projectDir).existsSync()) {
return true;
}
return false;
}
File _getManifestFile(Directory projectDir) {
return projectDir.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
}
/// Returns true if the `app` module AndroidManifest.xml includes the
/// <application android:name="${applicationName}"> attribute.
bool androidManifestHasNameVariable(final Directory projectDir) {
final File manifestFile = _getManifestFile(projectDir);
if (!manifestFile.existsSync()) {
return false;
}
XmlDocument document;
try {
document = XmlDocument.parse(manifestFile.readAsStringSync());
} on XmlException {
return false;
} on FileSystemException {
return false;
}
// Check for the ${androidName} application attribute.
for (final XmlElement application in document.findAllElements('application')) {
final String? applicationName = application.getAttribute('android:name');
if (applicationName == r'${applicationName}') {
return true;
}
}
return false;
}
......@@ -332,7 +332,6 @@ class AndroidBuildInfo {
],
this.splitPerAbi = false,
this.fastStart = false,
this.multidexEnabled = false,
});
// The build info containing the mode and flavor.
......@@ -350,9 +349,6 @@ class AndroidBuildInfo {
/// Whether to bootstrap an empty application.
final bool fastStart;
/// Whether to enable multidex support for apps with more than 64k methods.
final bool multidexEnabled;
}
/// A summary of the compilation strategy used for Dart.
......
......@@ -37,7 +37,6 @@ class BuildApkCommand extends BuildSubCommand {
addNullSafetyModeOptions(hide: !verboseHelp);
usesAnalyzeSizeFlag();
addAndroidSpecificBuildOptions(hide: !verboseHelp);
addMultidexOption();
addIgnoreDeprecationOption();
argParser
..addFlag('split-per-abi',
......@@ -134,7 +133,6 @@ class BuildApkCommand extends BuildSubCommand {
buildInfo,
splitPerAbi: boolArg('split-per-abi'),
targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName),
multidexEnabled: boolArg('multidex'),
);
validateBuild(androidBuildInfo);
displayNullSafetyMode(androidBuildInfo.buildInfo);
......
......@@ -42,7 +42,6 @@ class BuildAppBundleCommand extends BuildSubCommand {
addEnableExperimentation(hide: !verboseHelp);
usesAnalyzeSizeFlag();
addAndroidSpecificBuildOptions(hide: !verboseHelp);
addMultidexOption();
addIgnoreDeprecationOption();
argParser.addMultiOption('target-platform',
defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'],
......@@ -138,7 +137,6 @@ class BuildAppBundleCommand extends BuildSubCommand {
final AndroidBuildInfo androidBuildInfo = AndroidBuildInfo(await getBuildInfo(),
targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName),
multidexEnabled: boolArg('multidex'),
);
// Do all setup verification that doesn't involve loading units. Checks that
// require generated loading units are done after gen_snapshot in assemble.
......
......@@ -650,7 +650,6 @@ class AppDomain extends Domain {
String? packagesFilePath,
String? dillOutputPath,
bool ipv6 = false,
bool multidexEnabled = false,
String? isolateFilter,
bool machine = true,
String? userIdentifier,
......@@ -703,7 +702,6 @@ class AppDomain extends Domain {
projectRootPath: projectRootPath,
dillOutputPath: dillOutputPath,
ipv6: ipv6,
multidexEnabled: multidexEnabled,
hostIsIde: true,
machine: machine,
analytics: globals.analytics,
......@@ -715,7 +713,6 @@ class AppDomain extends Domain {
debuggingOptions: options,
applicationBinary: applicationBinary,
ipv6: ipv6,
multidexEnabled: multidexEnabled,
machine: machine,
);
}
......
......@@ -71,7 +71,6 @@ class DriveCommand extends RunCommandBase {
// to prevent a local network permission dialog on iOS 14+,
// which cannot be accepted or dismissed in a CI environment.
addPublishPort(enabledByDefault: false, verboseHelp: verboseHelp);
addMultidexOption();
argParser
..addFlag('keep-app-running',
help: 'Will keep the Flutter application running when done testing.\n'
......@@ -281,8 +280,6 @@ class DriveCommand extends RunCommandBase {
'trace-startup': traceStartup,
if (web)
'--no-launch-chrome': true,
if (boolArg('multidex'))
'multidex': true,
}
);
} else {
......
......@@ -337,7 +337,6 @@ class RunCommand extends RunCommandBase {
// This will allow subsequent "flutter attach" commands to connect to the VM
// without needing to know the port.
addPublishPort(verboseHelp: verboseHelp);
addMultidexOption();
addIgnoreDeprecationOption();
argParser
..addFlag('await-first-frame-when-tracing',
......@@ -640,7 +639,6 @@ class RunCommand extends RunCommandBase {
dillOutputPath: stringArg('output-dill'),
stayResident: stayResident,
ipv6: ipv6 ?? false,
multidexEnabled: boolArg('multidex'),
analytics: globals.analytics,
nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile),
);
......@@ -670,7 +668,6 @@ class RunCommand extends RunCommandBase {
: globals.fs.file(applicationBinaryPath),
ipv6: ipv6 ?? false,
stayResident: stayResident,
multidexEnabled: boolArg('multidex'),
);
}
......@@ -715,7 +712,6 @@ class RunCommand extends RunCommandBase {
packagesFilePath: globalResults![FlutterGlobalOptions.kPackagesOption] as String?,
dillOutputPath: stringArg('output-dill'),
ipv6: ipv6 ?? false,
multidexEnabled: boolArg('multidex'),
userIdentifier: userIdentifier,
enableDevTools: boolArg(FlutterCommand.kEnableDevTools),
);
......
......@@ -455,9 +455,7 @@ class FlutterDevice {
}
devFSWriter = device!.createDevFSWriter(applicationPackage, userIdentifier);
final Map<String, dynamic> platformArgs = <String, dynamic>{
'multidex': hotRunner.multidexEnabled,
};
final Map<String, dynamic> platformArgs = <String, dynamic>{};
await startEchoingDeviceLog(hotRunner.debuggingOptions);
......@@ -525,7 +523,6 @@ class FlutterDevice {
final Map<String, dynamic> platformArgs = <String, dynamic>{};
platformArgs['trace-startup'] = coldRunner.traceStartup;
platformArgs['multidex'] = coldRunner.multidexEnabled;
await startEchoingDeviceLog(coldRunner.debuggingOptions);
......
......@@ -21,7 +21,6 @@ class ColdRunner extends ResidentRunner {
this.traceStartup = false,
this.awaitFirstFrameWhenTracing = true,
this.applicationBinary,
this.multidexEnabled = false,
bool super.ipv6 = false,
super.stayResident,
super.machine,
......@@ -33,7 +32,6 @@ class ColdRunner extends ResidentRunner {
final bool traceStartup;
final bool awaitFirstFrameWhenTracing;
final File? applicationBinary;
final bool multidexEnabled;
bool _didAttach = false;
@override
......
......@@ -89,7 +89,6 @@ class HotRunner extends ResidentRunner {
super.stayResident,
bool super.ipv6 = false,
super.machine,
this.multidexEnabled = false,
super.devtoolsHandler,
StopwatchFactory stopwatchFactory = const StopwatchFactory(),
ReloadSourcesHelper reloadSourcesHelper = defaultReloadSourcesHelper,
......@@ -115,7 +114,6 @@ class HotRunner extends ResidentRunner {
final bool benchmarkMode;
final File? applicationBinary;
final bool hostIsIde;
final bool multidexEnabled;
/// When performing a hot restart, the tool needs to upload a new main.dart.dill to
/// each attached device's devfs. Replacing the existing file is not safe and does
......
......@@ -1015,15 +1015,6 @@ abstract class FlutterCommand extends Command<void> {
);
}
void addMultidexOption({ bool hide = false }) {
argParser.addFlag('multidex',
defaultsTo: true,
help: 'When enabled, indicates that the app should be built with multidex support. This '
'flag adds the dependencies for multidex when the minimum android sdk is 20 or '
'below. For android sdk versions 21 and above, multidex support is native.',
);
}
void addIgnoreDeprecationOption({ bool hide = false }) {
argParser.addFlag('ignore-deprecation',
negatable: false,
......
......@@ -595,61 +595,6 @@ void main() {
});
group('--machine', () {
testUsingContext('enables multidex by default', () async {
final DaemonCapturingRunCommand command = DaemonCapturingRunCommand();
final FakeDevice device = FakeDevice();
testDeviceManager.devices = <Device>[device];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--machine',
'-d',
device.id,
]),
throwsToolExit(),
);
expect(command.appDomain.multidexEnabled, isTrue);
}, overrides: <Type, Generator>{
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Usage: () => usage,
Stdio: () => FakeStdio(),
Logger: () => AppRunLogger(parent: BufferLogger.test()),
});
testUsingContext('can disable multidex with --no-multidex', () async {
final DaemonCapturingRunCommand command = DaemonCapturingRunCommand();
final FakeDevice device = FakeDevice();
testDeviceManager.devices = <Device>[device];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-multidex',
'--machine',
'-d',
device.id,
]),
throwsToolExit(),
);
expect(command.appDomain.multidexEnabled, isFalse);
}, overrides: <Type, Generator>{
Artifacts: () => artifacts,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
DeviceManager: () => testDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Usage: () => usage,
Stdio: () => FakeStdio(),
Logger: () => AppRunLogger(parent: BufferLogger.test()),
});
testUsingContext('can pass --device-user', () async {
final DaemonCapturingRunCommand command = DaemonCapturingRunCommand();
final FakeDevice device = FakeDevice(platformType: PlatformType.android);
......@@ -1570,7 +1515,6 @@ class DaemonCapturingRunCommand extends RunCommand {
class CapturingAppDomain extends AppDomain {
CapturingAppDomain(super.daemon);
bool? multidexEnabled;
String? userIdentifier;
bool? enableDevTools;
......@@ -1588,14 +1532,12 @@ class CapturingAppDomain extends AppDomain {
String? packagesFilePath,
String? dillOutputPath,
bool ipv6 = false,
bool multidexEnabled = false,
String? isolateFilter,
bool machine = true,
String? userIdentifier,
bool enableDevTools = true,
String? flavor,
}) async {
this.multidexEnabled = multidexEnabled;
this.userIdentifier = userIdentifier;
this.enableDevTools = enableDevTools;
throwToolExit('');
......
......@@ -117,7 +117,6 @@ void main() {
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
handlerCalled = true;
return GradleBuildStatus.exit;
......@@ -312,7 +311,6 @@ void main() {
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
return GradleBuildStatus.retry;
},
......@@ -415,7 +413,6 @@ void main() {
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
handlerCalled = true;
return GradleBuildStatus.exit;
......@@ -603,7 +600,6 @@ void main() {
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
return GradleBuildStatus.retry;
},
......
......@@ -332,7 +332,7 @@ tasks.register("clean", Delete) {
});
});
group('migrate min sdk versions less than 19 to flutter.minSdkVersion '
group('migrate min sdk versions less than 21 to flutter.minSdkVersion '
'when in a FlutterProject that is an app', ()
{
late MemoryFileSystem memoryFileSystem;
......@@ -359,32 +359,25 @@ tasks.register("clean", Delete) {
expect(bufferLogger.traceText, contains(appGradleNotFoundWarning));
});
testWithoutContext('replace when api 16', () {
const String minSdkVersion16 = 'minSdkVersion 16';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText));
});
testWithoutContext('replace when api 17', () {
const String minSdkVersion17 = 'minSdkVersion 17';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion17));
testWithoutContext('replace when api 19', () {
const String minSdkVersion19 = 'minSdkVersion 19';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText));
});
testWithoutContext('replace when api 18', () {
const String minSdkVersion18 = 'minSdkVersion 18';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion18));
testWithoutContext('replace when api 20', () {
const String minSdkVersion20 = 'minSdkVersion 20';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion20));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(replacementMinSdkText));
});
testWithoutContext('do nothing when >=api 19', () {
const String minSdkVersion19 = 'minSdkVersion 19';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19));
testWithoutContext('do nothing when >=api 21', () {
const String minSdkVersion21 = 'minSdkVersion 21';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion21));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion19));
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion21));
});
testWithoutContext('do nothing when already using '
......@@ -395,7 +388,7 @@ tasks.register("clean", Delete) {
});
testWithoutContext('avoid rewriting comments', () {
const String code = '// minSdkVersion 16 // old default\n'
const String code = '// minSdkVersion 19 // old default\n'
' minSdkVersion 23 // new version';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(code));
migration.migrate();
......@@ -411,10 +404,10 @@ tasks.register("clean", Delete) {
project,
bufferLogger
);
const String minSdkVersion16 = 'minSdkVersion 16';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion16));
const String minSdkVersion19 = 'minSdkVersion 19';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(minSdkVersion19));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion16));
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(minSdkVersion19));
});
testWithoutContext('do nothing when minSdkVersion is set '
......@@ -427,10 +420,10 @@ tasks.register("clean", Delete) {
testWithoutContext('do nothing when minSdkVersion is set '
'using = syntax', () {
const String equalsSyntaxMinSdkVersion16 = 'minSdkVersion = 16';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16));
const String equalsSyntaxMinSdkVersion19 = 'minSdkVersion = 19';
project.appGradleFile.writeAsStringSync(sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion19));
migration.migrate();
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion16));
expect(project.appGradleFile.readAsStringSync(), sampleModuleGradleBuildFile(equalsSyntaxMinSdkVersion19));
});
});
});
......
// Copyright 2014 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.
import 'package:file/file.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/multidex.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import '../../src/common.dart';
import '../../src/context.dart';
void main() {
testUsingContext('ensureMultidexUtilsExists patches file when invalid', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childDirectory('java')
.childDirectory('io')
.childDirectory('flutter')
.childDirectory('app')
.childFile('FlutterMultiDexApplication.java');
applicationFile.createSync(recursive: true);
applicationFile.writeAsStringSync('hello', flush: true);
expect(applicationFile.readAsStringSync(), 'hello');
ensureMultiDexApplicationExists(directory);
// File should remain untouched
expect(applicationFile.readAsStringSync(), '''
// Generated file.
//
// If you wish to remove Flutter's multidex support, delete this entire file.
//
// Modifications to this file should be done in a copy under a different name
// as this file may be regenerated.
package io.flutter.app;
import android.app.Application;
import android.content.Context;
import androidx.annotation.CallSuper;
import androidx.multidex.MultiDex;
/**
* Extension of {@link android.app.Application}, adding multidex support.
*/
public class FlutterMultiDexApplication extends Application {
@Override
@CallSuper
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
''');
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('ensureMultiDexApplicationExists generates when does not exist', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childDirectory('java')
.childDirectory('io')
.childDirectory('flutter')
.childDirectory('app')
.childFile('FlutterMultiDexApplication.java');
ensureMultiDexApplicationExists(directory);
final String contents = applicationFile.readAsStringSync();
expect(contents.contains('FlutterMultiDexApplication'), true);
expect(contents.contains('MultiDex.install(this);'), true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('multiDexApplicationExists false when does not exist', () async {
final Directory directory = globals.fs.currentDirectory;
expect(multiDexApplicationExists(directory), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('multiDexApplicationExists true when does exist', () async {
final Directory directory = globals.fs.currentDirectory;
final File utilsFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childDirectory('java')
.childDirectory('io')
.childDirectory('flutter')
.childDirectory('app')
.childFile('FlutterMultiDexApplication.java');
utilsFile.createSync(recursive: true);
expect(multiDexApplicationExists(directory), true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('androidManifestHasNameVariable true with valid manifest', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
applicationFile.createSync(recursive: true);
applicationFile.writeAsStringSync(r'''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multidexapp">
<application
android:label="multidextest2"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
</application>
</manifest>
''', flush: true);
expect(androidManifestHasNameVariable(directory), true);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('androidManifestHasNameVariable false with no android:name attribute', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
applicationFile.createSync(recursive: true);
applicationFile.writeAsStringSync(r'''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multidexapp">
<application
android:label="multidextest2"
android:icon="@mipmap/ic_launcher">
</application>
''', flush: true);
expect(androidManifestHasNameVariable(directory), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('androidManifestHasNameVariable false with incorrect android:name attribute', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
applicationFile.createSync(recursive: true);
applicationFile.writeAsStringSync(r'''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multidexapp">
<application
android:label="multidextest2"
android:name="io.flutter.app.FlutterApplication"
android:icon="@mipmap/ic_launcher">
</application>
''', flush: true);
expect(androidManifestHasNameVariable(directory), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('androidManifestHasNameVariable false with invalid xml manifest', () async {
final Directory directory = globals.fs.currentDirectory;
final File applicationFile = directory.childDirectory('android')
.childDirectory('app')
.childDirectory('src')
.childDirectory('main')
.childFile('AndroidManifest.xml');
applicationFile.createSync(recursive: true);
applicationFile.writeAsStringSync(r'''
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multidexapp">
<application
android:label="multidextest2"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
</application>
''', flush: true);
expect(androidManifestHasNameVariable(directory), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('androidManifestHasNameVariable false with no manifest file', () async {
final Directory directory = globals.fs.currentDirectory;
expect(androidManifestHasNameVariable(directory), false);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
}
// Copyright 2014 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.
import 'package:file/file.dart';
import 'package:flutter_tools/src/base/io.dart';
import '../src/common.dart';
import 'test_data/multidex_project.dart';
import 'test_driver.dart';
import 'test_utils.dart';
void main() {
late Directory tempDir;
late FlutterRunTestDriver flutter;
setUp(() async {
tempDir = createResolvedTempDirectorySync('run_test.');
flutter = FlutterRunTestDriver(tempDir);
});
tearDown(() async {
await flutter.stop();
tryToDelete(tempDir);
});
testWithoutContext('simple build apk succeeds', () async {
final MultidexProject project = MultidexProject(true);
await project.setUpIn(tempDir);
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
final ProcessResult result = await processManager.run(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
'apk',
'--debug',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher(stdoutPattern: 'app-debug.apk'));
});
testWithoutContext('simple build apk without FlutterMultiDexApplication fails', () async {
final MultidexProject project = MultidexProject(false);
await project.setUpIn(tempDir);
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
final ProcessResult result = await processManager.run(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
'apk',
'--debug',
], workingDirectory: tempDir.path);
expect(result, const ProcessResultMatcher(exitCode: 1));
expect(result.stderr.toString(), contains('Cannot fit requested classes in a single dex file'));
expect(result.stderr.toString(), contains('The number of method references in a .dex file cannot exceed 64K.'));
});
}
......@@ -87,7 +87,7 @@ class DeferredComponentModule {
}
defaultConfig {
minSdkVersion 19
minSdkVersion 21
targetSdkVersion 33
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
......
......@@ -43,7 +43,7 @@ android {
}
defaultConfig {
minSdkVersion 19
minSdkVersion 21
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'lib-proguard-rules.txt'
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment