构建-0 Gradle DSL 属性和方法【API】

时间:2021-05-02 13:51:56

Android Plugin DSL Reference

This is the DSL reference for Android Gradle Plugin.
Start reading by finding the right extension type for the plugin you are using, e.g. AppExtension.

Listed below are the Gradle extension扩展 types used by respective各自的 plugins:
Type Description
AppExtension

The android extension for com.android.application projects.

LibraryExtension

The android extension for com.android.library projects.

Apply this plugin to your project to create an Android library.

TestExtension

android extension for com.android.test projects.

FeatureExtension

The android extension for com.android.feature projects.

Creating feature modules is useful when you want to build Android Instant Apps. To learn more about creating feature modules, read Structure of an instant app with multiple features.


Listed below are the configuration blocks available within android
Block Description
aaptOptions { }

Specifies options for the Android Asset Packaging Tool (AAPT).

adbOptions { }

Specifies options for the Android Debug Bridge (ADB), such as APK installation options.

buildTypes { }

Encapsulates all build type configurations for this project.

compileOptions { }

Specifies Java compiler options, such as the language level of the Java source code and generated bytecode.

dataBinding { }

Specifies options for the Data Binding Library.

defaultConfig { }

Specifies defaults for variant properties that the Android plugin applies to all build variants.

dexOptions { }

Specifies options for the DEX tool, such as enabling library pre-dexing.

externalNativeBuild

Configures external native build using CMake or ndk-build.

jacoco { }

Configuring JaCoCo using this block is deprecated.

lintOptions { }

Specifies options for the lint tool.

packagingOptions

Specifies options and rules that determine which files the Android plugin packages into your APK.

productFlavors { }

Encapsulates all product flavors configurations for this project.

signingConfigs { }

Encapsulates signing configurations that you can apply to BuildType and ProductFlavor configurations.

sourceSets { }

Encapsulates source set configurations for all variants.

splits { }

Specifies configurations for building multiple APKs or APK splits.

testOptions { }

Specifies options for how the Android plugin should run local and instrumented tests.


buildTypes

buildTypes {
	release {
	    debuggable false
	}
	debug {
	}
	pre {
	    initWith release
	    debuggable true
	}
}

属性

String applicationIdSuffix
Application id suffix. It is appended to the "base" application id when calculating the final application id for a variant.
In case there are product flavor dimensions specified, the final application id suffix will contain the suffix from the default product flavor, followed by the suffix from product flavor of the first dimension, second dimension and so on. All of these will have a dot in between e.g. "defaultSuffix .dimension1Suffix .dimensions2Suffix".

List<File> consumerProguardFiles
ProGuard rule files to be included in the published AAR.
These proguard rule files will then be used by any application project that consumes the AAR (if ProGuard is enabled).
This allows AAR to specify shrinking or obfuscation exclude rules 这允许AAR指定压缩或混淆排除规则。.
This is only valid有效的 for Library project. This is ignored in Application project.

Boolean crunchPngs
Whether to crunch PNGs.
Setting this property to true reduces减少 of PNG resources that are not already optimally最佳、最优 compressed. However, this process increases build times.
PNG crunching is enabled by default in the release build type and disabled by default in the debug build type.

boolean debuggable
Whether this build type should generate a debuggable apk.

boolean embedMicroApp
Whether a linked链接的 Android Wear app should be embedded嵌入 in variant using this build type.
Wear apps can be linked with the following code:
dependencies {
  freeWearApp project(:wear:free') // applies to variant using the free flavor
  wearApp project(':wear:base') // applies to all other variants
}

com.android.build.gradle.api.JavaCompileOptions javaCompileOptions
Options for configuration Java compilation.

boolean jniDebuggable
Whether this build type is configured to generate an APK with debuggable native code.

Map<String, Object> manifestPlaceholders
The manifest placeholders.  See Inject Build Variables into the Manifest.

List<String> matchingFallbacks
Fallbacks:回退
Specifies a sorted list of build types that the plugin should try to use when a direct variant match with a local module dependency is not possible.
指定当直接 variant 与本地 module dependency 不匹配时插件应尝试使用的 build types 的排序列表。

Android plugin 3.0.0 and higher try to match each variant of your module with the same one from its dependencies. For example, when you build a "freeDebug" version of your app, the plugin tries to match it with "freeDebug" versions of the local library modules the app depends on.
Android插件3.0.0及更高版本尝试将 module 的每个 variant 与其 dependencies 中的相同 variant 匹配。 例如,当您构建应用程序的“freeDebug”版本时,插件会尝试将其与应用程序所依赖的本地 library modules 的“freeDebug”版本进行匹配。

However, there may be situations in which your app includes build types that a dependency does not. For example, consider if your app includes a "stage" build type, but a dependency includes only a "debug" and "release" build type. When the plugin tries to build the "stage" version of your app, it won't know which version of the dependency to use, and you'll see an error message similar to the following:
但是,在某些情况下,您的应用程序可能包含 dependency 不包含的 build types。 例如,假设您的应用包含“stage”构建类型,但依赖项仅包括“debug”和“release”构建类型。 当插件尝试构建应用程序的“stage”版本时,它将不知道要使用哪个版本的依赖项,并且您将看到类似于以下内容的错误消息:
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
    project :app

In this situation, you can use matchingFallbacks to specify alternative matches for the app's "stage" build type, as shown below:
在这种情况下,您可以使用matchingFallbacks为应用程序的“stage”构建类型指定替代匹配,如下所示:
// In the app's build.gradle file.
android {
    buildTypes {
        release {
            // Because the dependency already includes a "release" build type, you don't need to provide a list of fallbacks here.
        }
        stage {
/** Specifies a sorted list of fallback build types that the plugin should try to use when a dependency does not include a "stage" build type. You may specify as many fallbacks as you like, and the plugin selects the first build type that's available in the dependency. */
            matchingFallbacks = ['debug', 'qa', 'release']
        }
    }
}
Note that there is no issue when a library dependency includes a build type that your app does not. That's because the plugin simply never requests that build type from the dependency.
请注意,当 library dependency 包含您应用程序中不包含的 build type 时并没有问题,因为插件根本不会从 dependency 中请求 build type。

boolean minifyEnabled
Whether removal of unused java code is enabled.
Default is false.

Boolean multiDexEnabled
Whether Multi-Dex is enabled for this variant.

File multiDexKeepFile
Text file that specifies additional classes that will be compiled into the main dex file.
Classes specified in the file are appended to the main dex classes computed using aapt.
If set, the file should contain one class per line, in the following format: 
com/example/MyClass.class

File multiDexKeepProguard
Text file with additional ProGuard rules to be used to determine which classes are compiled into the main dex file.
If set, rules from this file are used in combination with the default rules used by the build system.

String name
Name of this build type.

PostprocessingOptions postprocessing
note: this property is incubating and may change in a future version of the plugin.
This DSL is incubating and subject to change.

List<File> proguardFiles
Specifies the ProGuard configuration files that the plugin should use.
There are two ProGuard rules files that ship船 with the Android plugin and are used by default:
  • proguard-android.txt
  • proguard-android-optimize.txt
proguard-android-optimize.txt is identical完全相同的 to proguard-android.txt , exccept with optimizations enabled. You can use getDefaultProguardFile(String filename) to return the full path of the files.

boolean pseudoLocalesEnabled
Specifies whether the plugin should generate resources for pseudolocales.
A pseudolocale is a locale that simulates characteristics模拟特征 of languages that cause UI, layout, and other translation-related翻译相关的 problems when an app is localized本地化. Pseudolocales can aid援助 your development workflow工作流 because you can test and make adjustments调整 to your UI before you finalize完成 text for translation.
When you set this property to true as shown below, the plugin generates resources for the following pseudo locales and makes them available in your connected device's language preferences: en-XA and ar-XB.
android {
    buildTypes {
        debug {
            pseudoLocalesEnabled true
        }
    }
}
When you build your app, the plugin includes包括 the pseudolocale resources in your APK. If you notice that your APK does not include those locale resources, make sure your build configuration isn't limiting which locale resources are packaged with your APK, such as using the resConfigs property to remove unused locale resources.
To learn more, read Test Your App with Pseudolocales.

boolean renderscriptDebuggable
Whether the build type is configured to generate an apk with debuggable RenderScript code.

int renderscriptOptimLevel
Optimization level to use by the renderscript compiler.

boolean shrinkResources
Whether shrinking of unused resources is enabled. Default is false;

SigningConfig signingConfig
The signing configuration.

boolean testCoverageEnabled
Whether test coverage覆盖 is enabled for this build type.
If enabled this uses Jacoco to capture coverage and creates a report in the build directory.
The version of Jacoco can be configured with:
android {
  jacoco {
    version = '0.6.2.201302030002'
  }
}

Boolean useProguard
Specifies whether to always use ProGuard for code and resource shrinking.
By default, when you enable code shrinking by setting minifyEnabled to true, the Android plugin uses ProGuard. However while deploying your app using Android Studio's Instant Run feature, which doesn't support ProGuard, the plugin switches to using a custom experimental实验的 code shrinker.
If you experience issues using the experimental code shrinker 如果使用实验性代码缩减器时遇到问题, you can disable code shrinking while using Instant Run by setting this property to true.
To learn more, read Shrink Your Code and Resources.

String versionNameSuffix
Version name suffix. It is appended to the "base" version name when calculating the final version name for a variant.
In case there are product flavor dimensions specified, the final version name suffix will contain the suffix from the default product flavor, followed by the suffix from product flavor of the first dimension, second dimension and so on.

boolean zipAlignEnabled
Whether zipalign is enabled for this build type.

方法

void buildConfigField(String type, String name, String value)
Adds a new field to the generated BuildConfig class.
The field is generated as: <type> <name> = <value>;
This means each of these must have valid Java content. If the type is a String, then the value should include quotes引号.
buildConfigField "boolean", "isHongkongUser", "true"
buildConfigField "int", "countryCode", "20094"
buildConfigField "String", "BASE_URL", '"http://110.com/"'

BuildType consumerProguardFile(Object proguardFile)
BuildType consumerProguardFiles(Object... proguardFiles)
Adds a proguard rule file to be included in the published AAR.
This proguard rule file will then be used by any application project that consume the AAR (if proguard is enabled).
This allows AAR to specify指定 shrinking or obfuscation exclude rules缩小或混淆排除规则.
This is only valid有效的 for Library project. This is ignored in Application project.

ExternalNativeBuildOptions externalNativeBuild(Action<ExternalNativeBuildOptions> action)
Configure native build options.

DefaultBuildType initWith(BuildType that)
Copies all properties from the given build type.

BuildType proguardFile(Object proguardFile)
BuildType proguardFiles(Object... files)
Adds a new ProGuard configuration file(s).
There are 2 default rules files
  • proguard-android.txt
  • proguard-android-optimize.txt
They are located in the SDK. Using getDefaultProguardFile(String filename) will return the full path to the files. They are identical完全相同的 except for enabling optimizations.

void resValue(String type, String name, String value)
Adds a new generated resource.
This is equivalent to specifying a resource in res/values.

BuildType setProguardFiles(Iterable<?> proguardFileIterable)
Sets the ProGuard configuration files.

脚本块

Script block
postprocessing {
}
note: this script block is incubating潜伏、培育、孵化 and may change in a future version of the plugin.
This DSL is incubating and subject to change.
Delegates代表、委托、委派 to:  PostprocessingOptions from postprocessing

productFlavors 和 defaultConfig

productFlavors {
    productA {
    }

    productB {
    }

    productFlavors.all {
    }

    android.applicationVariants.all { variant ->
        variant.outputs.all { output ->
            variant.productFlavors.each { flavor ->
                ...
            }
        }
    }
}
封装[Encapsulates]此项目的所有产品风格属性。

配置产品风格类似于配置构建类型:将它们添加到模块的 build.gradle 文件的 productFlavors 块并配置所需的设置。产品风格支持与 BaseExtension.getDefaultConfig() 块相同的属性 - 这是因为 defaultConfig 定义了一个 ProductFlavor 对象,该插件使用该对象作为所有其他风格的基本配置。然后,您配置的每个 flavor 都可以覆盖 defaultConfig 中的任何默认值,例如 applicationId。

属性

和 BuildType 相同的属性:
  • String applicationIdSuffix
  • List<File> consumerProguardFiles
  • JavaCompileOptions javaCompileOptions
  • Map<String, Object> manifestPlaceholders
  • List<String> matchingFallbacks
  • Boolean multiDexEnabled
  • File multiDexKeepFile
  • File multiDexKeepProguard
  • List<File> proguardFiles
  • SigningConfig signingConfig
  • String versionNameSuffix

几个非常简单的属性:
  • String applicationId
  • String testApplicationId
  • Integer versionCode
  • String versionName
  • String dimension

和仪表、仪器相关的属性:
详见 instrumentation 。
  • Boolean testFunctionalTest  功能性测试
  • Boolean testHandleProfiling  处理分析
  • String testInstrumentationRunner  测试仪表
    • Test instrumentation runner class name.
    • This is a fully qualified class name of the runner, e.g. android.test.InstrumentationTestRunner
  • Map<String, String> testInstrumentationRunnerArguments  测试仪表参数
    • Test instrumentation runner custom arguments.
    • e.g. [key: "value"] will give adb shell am instrument -w -e key value com.example...".

ExternalNativeBuildOptions externalNativeBuild
Encapsulates per-variant CMake and ndk-build configurations for your external native build.

Set<String> generatedDensities
note: this property is deprecated废弃 and will be removed in a future version of the plugin.
Deprecated equivalent of等价于 vectorDrawablesOptions.generatedDensities.

Boolean wearAppUnbundled
Returns whether to enable unbundling mode for embedded wear app. If true, this enables the app to transition from an embedded wear app to one distributed by the play store directly.

NdkOptions ndk
Encapsulates per-variant configurations for the NDK, such as ABI filters.

方法

和 BuildType 相同的方法:
  • void buildConfigField(String type, String name, String value)
  • void resConfigs(String... config)
  • void resConfigs(Collection<String> config)
  • void resConfig(String config)
  • void resValue(String type, String name, String value)

SDK版本号相关的方法:
  • void maxSdkVersion(int maxSdkVersion)
  • void minSdkVersion(int minSdkVersion)
  • void minSdkVersion(String minSdkVersion)
  • void targetSdkVersion(int targetSdkVersion)
  • void targetSdkVersion(String targetSdkVersion)

混淆文件 Proguard 相关的方法:
  • void consumerProguardFile(Object proguardFile)
  • void consumerProguardFiles(Object... proguardFiles)
  • void proguardFile(Object proguardFile)
  • void proguardFiles(Object... files)
  • void setProguardFiles(Iterable<?> proguardFileIterable)
  • void setConsumerProguardFiles(Iterable<?> proguardFileIterable)
  • void setTestProguardFiles(Iterable<?> files)
  • void testProguardFile(Object proguardFile)
  • void testProguardFiles(Object... proguardFiles)

仪器测试时添加参数:
  • void testInstrumentationRunnerArgument(String key, String value)
  • void testInstrumentationRunnerArguments(Map<String, String> args)
Adds a custom argument to the test instrumentation仪器仪表 runner,例如:
testInstrumentationRunnerArgument "size", "medium"
Test runner arguments can also be specified from the command line:
./gradlew connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.size=medium

缺失维度的匹配策略:
作用类似于 BuildType 里面的 matchingFallbacks
  • void missingDimensionStrategy(String dimension, String requestedValue)
  • void missingDimensionStrategy(String dimension, String... requestedValues)
  • void missingDimensionStrategy(String dimension, List<String> requestedValues)
Specifies a sorted list of flavors that the plugin should try to use from a given dimension in a dependency.
指定插件应尝试从 dependency 中的给定 dimension 使用的排序 flavors 列表。

Android plugin 3.0.0 and higher try to match each variant of your module with the same one from its dependencies. For example, consider if both your app and its dependencies include a "tier" flavor dimension, with flavors "free" and "paid". When you build a "freeDebug" version of your app, the plugin tries to match it with "freeDebug" versions of the local library modules the app depends on.
Android插件3.0.0及更高版本尝试将模块的每个变体与其依赖项中的相同变体匹配。 例如,考虑您的应用程序及其依赖项是否包含“层”风格维度,其中包含“免费”和“付费”的风格。 当您构建应用程序的“freeDebug”版本时,插件会尝试将其与应用程序所依赖的本地库模块的“freeDebug”版本进行匹配。

However, there may be situations in which a library dependency includes a flavor dimension that your app does not. For example, consider if a library dependency includes flavors for a "minApi" dimension, but your app includes flavors for only the "tier" dimension. So, when you want to build the "freeDebug" version of your app, the plugin doesn't know whether to use the "minApi23Debug" or "minApi18Debug" version of the dependency, and you'll see an error message similar to the following:
但是,在某些情况下,库依赖项包含应用程序不具有的 flavor dimension。 例如,考虑库依赖项是否包含“minApi”维度的风格,但您的应用程序仅包含“层”维度的风格。 因此,当您想要构建应用程序的“freeDebug”版本时,插件不知道是否使用依赖项的“minApi23Debug”或“minApi18Debug”版本,您将看到类似于以下内容的错误消息:
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
    project :app

In this type of situation, use missingDimensionStrategy in the defaultConfig block to specify the default flavor the plugin should select from each missing dimension, as shown in the sample below. You can also override your selection in the productFlavors block, so each flavor can specify a different matching strategy for a missing dimension. (Tip: you can also use this property if you simply want to change the matching strategy for a dimension that exists in both the app and its dependencies.)
在这种情况下,使用defaultConfig块中的missingDimensionStrategy指定插件应从每个缺失维度中选择的默认flavor,如下面的示例所示。 您还可以在productFlavors块中覆盖您的选择,这样每种风格都可以为缺少的维度指定不同的匹配策略。(提示:如果您只想更改应用及其依赖项中存在的维度的匹配策略,也可以使用此属性。)
// In the app's build.gradle file.
android {
    defaultConfig{
/** Specifies a sorted list of flavors that the plugin should try to use from a given dimension. The following tells the plugin that, when encountering a dependency that includes a "minApi" dimension, it should select the "minApi18" flavor. You can include additional flavor names to provide a sorted list of fallbacks for the dimension. */
    missingDimensionStrategy 'minApi', 'minApi18', 'minApi23'
/** You should specify a missingDimensionStrategy property for each dimension that exists in a local dependency but not in your app. */
    missingDimensionStrategy 'abi', 'x86', 'arm64'
    }
    flavorDimensions 'tier'
    productFlavors {
        free {
            dimension 'tier'
/** You can override the default selection at the product flavor level by configuring another missingDimensionStrategy property for the "minApi" dimension. */
            missingDimensionStrategy 'minApi', 'minApi23', 'minApi18'
        }
        paid {}
    }
}

NdkOptions 

ndk 属性的值是一个  NdkOptions  ,它里面只有一个属性可以设置,就是 abiFilters。
Set<String> abiFilters
Specifies the Application Binary Interfaces (ABI) that Gradle should build outputs for and package with your APK.
You can list any subset of the ABIs the NDK supports, as shown below:
android {
    defaultConfig {
        ndk {
            abiFilters 'x86', 'x86_64', 'armeabi' // Tells Gradle to build outputs for the following ABIs and package them into your APK.
        }
    }
}
When this flag is not configured, Gradle builds and packages all available ABIs.
To reduce减少 the size of your APK, consider configuring multiple APKs based on ABI—instead of creating one large APK with all versions of your native libraries, Gradle creates a separate APK for each ABI you want to support and only packages the files each ABI needs.

Android 设备 支持的CPU类型(ABIs):
  • armeabi:第5代、第6代的ARM处理器,早期的手机用的比較多。
  • armeabiv-v7a:第7代及以上的 ARM 处理器。2011年15月以后的生产的大部分Android设备都使用它.
  • arm64-v8a:第8代、64位ARM处理器,非常少设备,三星 Galaxy S6是当中之中的一个。
  • x86:平板、模拟器用得比較多。
  • x86_64:64位的平板。
  • mips
  • mips64
Android Plugin for Gradle 3.1.0 and higher no longer generate APKs for the following ABIs by default: mips, mips64, and armeabi. That's because NDK r17 and higher no longer include these ABIs as supported targets.

signingConfigs

  • String keyAlias    Key alias used when signing.
  • String keyPassword    Key password used when signing.
  • File storeFile    Store file used when signing.
  • String storePassword    Store password used when signing.
  • String storeType    Store type used when signing.
  • boolean v1SigningEnabled    Whether signing using JAR Signature Scheme (aka v1 signing) is enabled.
  • boolean v2SigningEnabled    Whether signing using APK Signature Scheme v2 (aka v2 signing) is enabled.

sourceSets

Encapsulates source set configurations for all variants.
Note that the Android plugin uses its own implementation of source sets. For more information about the properties you can configure in this block, see AndroidSourceSet.
android {
  sourceSets {
    main {
      java.srcDirs = ['other/java'] //default is 'src/main/java'.
      res.srcDirs = ['other/res1', 'other/res2'] //default is 'src/main/res'
      manifest.srcFile 'other/AndroidManifest.xml'
    }

    androidTest {  // Create additional blocks to configure other source sets.
      setRoot 'src/tests'
    }
  }
}

AndroidSourceSet 

An AndroidSourceSet represents a logical group of Java, aidl and RenderScript sources as well as Android and non-Android (Java-style) resources.

属性:
  • AndroidSourceDirectorySet  aidl  The Android AIDL source directory for this source set.
  • AndroidSourceDirectorySet  assets  The Android Assets directory for this source set.
  • String  compileConfigurationName    deprecated   The name of the compile configuration for this source set.
  • AndroidSourceDirectorySet  java   The Java source which is to be compiled by the Java compiler into the class output directory.
  • AndroidSourceDirectorySet  jni   The Android JNI source directory for this source set.
  • AndroidSourceDirectorySet  jniLibs    The Android JNI libs directory for this source set.
  • AndroidSourceFile  manifest    The Android Manifest file for this source set.
  • String  name    The name of this source set.
  • String  packageConfigurationName    deprecated  The name of the runtime configuration for this source set.
  • String  providedConfigurationName    deprecated  The name of the compiled-only configuration for this source set.
  • AndroidSourceDirectorySet  renderscript    The Android RenderScript source directory for this source set.
  • AndroidSourceDirectorySet  res    The Android Resources directory for this source set.
  • AndroidSourceDirectorySet  resources    The Java resources which are to be copied into the javaResources output directory.
方法:
  • AndroidSourceSet setRoot(path)    Sets the root of the source sets to a given path. All entries of the source set are located under this root directory.

AndroidSourceFile 

  • 属性:String nameA concise name for the source directory (typically used to identify it in a collection).
  • 属性:File srcFileThe file.
  • 方法:AndroidSourceFile srcFile(Object srcPath)Sets the location of the file. Returns this object.

AndroidSourceDirectorySet 

属性:
  • PatternFilterable filterThe filter used to select the source from the source directories.
  • String nameA concise name for the source directory (typically used to identify it in a collection).
  • FileTree sourceFilesThe list of source files as a FileTree
  • Set<File> srcDirsThe resolved directories. Setter can be called with a collection of Objects, just like Gradle's project.file(...).

方法:
  • AndroidSourceDirectorySet srcDir(Object srcDir)Adds the given source directory to this set.
  • AndroidSourceDirectorySet srcDirs(Object... srcDirs)Adds the given source directories to this set.

splits

用于配置APK Splits选项的DSL对象。 配置此对象允许您构建 Multiple APKs  and  Configuration APKs

如果您的应用针对多种设备配置[targets multiple device configurations],例如不同的屏幕密度和  Application Binary Interfaces (ABIs),您可能希望避免将所有配置的资源打包到单个大型APK中。 为了减少用户下载大小,Android插件和Google Play商店提供了以下策略来生成和提供每个针对不同设备配置的 build artifiacts - 因此用户只下载他们需要的资源:
  • Multiple APKs:使用此功能生成多个独立的[stand-alone]APK。每个APK都包含给定设备配置所需的代码和资源。 Android插件和Google Play商店支持根据屏幕密度和ABI生成多个APK。由于每个APK都代表您上传到Google Play商店的独立APK,因此请确保为每个APK分配 appropriately 版本代码,以便以后能够管理更新。
  • Configuration APKs:仅在您构建 Android Instant Apps 时使用此功能。 Android插件将应用程序中与设备无关的[device-agnostic]代码和资源打包到基本APK中,并将每组设备相关的[device-dependent]二进制文件和资源打包在单独的[separate]APK中,称为 Configuration APKs。Configuration APKs不代表您应用的独立版本[stand-alone versions]。也就是说,设备需要从Google Play商店下载基本APK和其他 Configuration APKs 才能运行您的 instant app。 Android插件和Google Play商店支持根据屏幕密度,ABI和语言区域[language locales]设置生成配置APK。您可以像在构建多个APK时一样指定此块中的属性。但是,您还需要将generatePureSplits设置为true。

属性

  • AbiSplitOptions  abi   Encapsulates settings for building per-ABI APKs.
  • Set<String>  abiFilters   The list of ABIs that the plugin will generate separate APKs for.
    • If this property returns null, it means the plugin will not generate separate per-ABI APKs. That is, each APK will include binaries for all ABIs your project supports.
  • DensitySplitOptions  density  Encapsulates settings for building per-density APKs.
  • Set<String>  densityFilters   The list of screen density configurations that the plugin will generate separate APKs for.
    • If this property returns null, it means the plugin will not generate separate per-density APKs. That is, each APK will include resources for all screen density configurations your project supports.
  • LanguageSplitOptions  language   Encapsulates settings for building per-language (or locale) APKs.
  • Set<String>  languageFilters   The list of languages (or locales) that the plugin will generate separate APKs for.
    • If this property returns null, it means the plugin will not generate separate per-language APKs. That is, each APK will include resources for all languages your project supports.

脚本块

Script block
abi { }
density { }
language { }

AbiSplitOptions 和 DensitySplitOptions

两者都有的属性:
  • Set<String> applicableFiltersReturns a list of all applicable可用的、适用的 filters for this dimension.
    • The list can return null, indicating表明、指示 that the no-filter option must also be used.
  • boolean enableWhether to split in this dimension.

AbiSplitOptions 中特有的属性:
  • boolean universalApkWhether to create an FULL_APK with all available ABIs.

DensitySplitOptions 中特有的属性:
  • boolean autoWhether the build system should determine the splits based on the "language-*" folders in the resources.
    • If the auto mode is set to true, the include list will be ignored.
  • Set<String> compatibleScreensA list of compatible screens.
    • This will inject a matching <compatible-screens><screen ...> node in the manifest. This is optional.

方法:
  • void exclude(String... excludes)excludes排除 some values
  • void include(String... includes)includes some values
  • void reset()Resets the list of included split configuration.
    • Use this before calling include, in order to manually手动 configure the list of configuration to split on, rather than excluding from the default list.

LanguageSplitOptions

Encapsulates settings for building per-language (or locale) APKs.
Note: Building per-language APKs is supported only when building configuration APKs for Android Instant Apps.
  • 属性:boolean enable  Returns true if splits should be generated for languages.
  • 方法:void include(String... includes)  Adds an include pattern.

variantFilter

属性:
  • BuildType buildType  The Build Type.
  • ProductFlavor defaultConfig  The ProductFlavor that represents the default config.
  • List<ProductFlavor> flavors  The list of flavors, or an empty list.
方法:
  • void setIgnore(boolean ignore)  Sets whether or not to ignore this particular特别的 variant. Default is false.
variantFilter { variant ->
    def names = variant.flavors*.name
    if (names.contains("sex2") || names.contains("productC")) { // variant.buildType.name == "<buildType>"
        setIgnore(true)// Gradle ignores any variants that satisfy the conditions above.
    }
}

dexOptions

  • List<String> additionalParametersList of additional parameters to be passed to dx.
  • String javaMaxHeapSizeSpecifies the -Xmx value when calling dx. Example value is "2048m".
  • boolean jumboModeEnable jumbo巨大的、庞然大物的 mode in dx (--force-jumbo).
  • boolean keepRuntimeAnnotatedClassesKeep all classes with runtime annotations in the main dex in legacy传统的、遗产 multidex.
    • This is enabled by default and works around an issue that will cause the app to crash when using java.lang.reflect.Field.getDeclaredAnnotations on older android versions.
    • This can be disabled for apps that do not use reflection and need more space in their main dex.
    • See http://b.android.com/78144.
  • Integer maxProcessCountThe maximum number of concurrent processes that can be used to dex. Defaults to 4.
    • Be aware that the number of concurrent并发 process进程 times乘以 the memory requirement represent代表 the minimum amount of memory that will be used by the dx processes:
    • Total Memory = maxProcessCount * javaMaxHeapSize
    • To avoid thrashing超负荷, keep these two settings appropriate适当的 for your configuration.
  • boolean preDexLibrariesWhether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.
  • Integer threadCountNumber of threads to use when running dx. Defaults to 4.
建议配置:
android {
  dexOptions {
    maxProcessCount 8 // Sets the maximum number of DEX processes that can be started concurrently.
    javaMaxHeapSize "2g" // Sets the maximum memory allocation pool size for the dex operation.
    preDexLibraries true // Enables Gradle to pre-dex library dependencies.
  }
}

lintOptions

属性:
  • boolean abortOnError  Whether lint should set the exit code of the process if errors are found
  • boolean absolutePaths  Whether lint should display full paths in the error output. By default the paths are relative to the path lint was invoked调用、叫唤 from.
  • Set<String> check  The exact set of issues to check要检查的确切问题集, or null to run the issues that are enabled by default plus加上 any issues enabled via LintOptions.getEnable() and without issues disabled via LintOptions.getDisable(). If non-null, callers are allowed to modify this collection.
    • To enable checks for only a subset of issue IDs and ignore all others, list the issue IDs with the 'check' property instead. 
    • This property overrides any issue IDs you enable or disable.
  • boolean checkAllWarnings  Returns whether lint should check all warnings, including those off by default
  • boolean checkReleaseBuilds  Returns whether lint should check for fatal致命的 errors during release builds. Default is true. If issues with severity "fatal" are found, the release build is aborted.
  • Set<String> disable  The set of issue id's to suppress压制、禁止. Callers are allowed to modify this collection.
  • Set<String> enable  The set of issue id's to enable. Callers are allowed to modify this collection. To enable a given issue, add the issue ID to the returned set.
  • boolean explainIssues  Returns whether lint should include explanations解释 for issue errors. (Note that HTML and XML reports intentionally特意的、故意的、有意的 do this unconditionally无条件的, ignoring this setting.)
  • File htmlOutput  The optional path to where an HTML report should be written
  • boolean htmlReport  Whether we should write an HTML report. Default true. The location can be controlled by LintOptions.getHtmlOutput().
  • boolean ignoreWarnings  Returns whether lint will only check for errors (ignoring warnings)
  • File lintConfig  The default configuration file to use as a fallback回退、撤退、回调
  • boolean noLines  Whether lint should include the source lines in the output where errors occurred (true by default)
  • boolean quiet  Returns whether lint should be quiet (for example, not write informational messages不写信息性消息 such as paths to report files written例如报告文件的路径)
  • Map<String, Integer> severityOverrides  An optional map of severity严重性 overrides. The map maps from issue id's to the corresponding severity to use映射从问题ID映射到要使用的相应严重性, which must be "fatal", "error", "warning", or "ignore".
  • boolean showAll  Returns whether lint should include all output (e.g. include all alternate替换的 locations, not truncating截断 long messages, etc.)
  • File textOutput  The optional path to where a text report should be written. The special value "stdout"标准输出 can be used to point to standard output.
  • boolean textReport  Whether we should write an text report. Default false. The location can be controlled by LintOptions.getTextOutput().
  • boolean warningsAsErrors  Returns whether lint should treat all warnings as errors
  • File xmlOutput  The optional path to where an XML report should be written
  • boolean xmlReport  Whether we should write an XML report. Default true. The location can be controlled by LintOptions.getXmlOutput().

方法:
  • void check(String id) 和 check(String... ids)  Adds the ids to the set of issues to check.
  • void disable(String id) 和 disable(String... ids)  Adds the ids to the set of issues to enable.
  • void enable(String id) 和 enable(String... ids)  Adds the ids to the set of issues to enable.
  • void error(String id) 和 error(String... ids)  Adds a severity override for the given issues.
  • void fatal(String id) 和 fatal(String... ids)致命的、重大的  Adds a severity override for the given issues.
  • void ignore(String id) 和 ignore(String... ids)  Adds a severity override for the given issues.
  • void warning(String id) 和 warning(String... ids)  Adds a severity override for the given issues.

testOptions

属性:
  • boolean animationsDisabled  Disables animations during instrumented tests.
  • String execution  Specifies whether to use on-device设备上的 test orchestration配器、编曲、编排.
    • If you want to use Android Test Orchestrator, you need to specify "ANDROID_TEST_ORCHESTRATOR", as shown below. 
    • By default, this property is set to "HOST", which disables on-device orchestration.
android {
  testOptions {
    execution 'ANDROID_TEST_ORCHESTRATOR'
  }
}
  • String reportDir  Name of the reports directory.
  • String resultsDir  Name of the results directory.
  • UnitTestOptions unitTests  Configures unit test options.

脚本块
unitTests { }
Configures unit test options.
Delegates to: UnitTestOptions from unitTests

UnitTestOptions

  • 属性:boolean includeAndroidResourcesEnables unit tests to use Android resources, assets, and manifests.
    • If you set this property to true, the plugin performs resource, asset, and manifest merging before running your unit tests. Your tests can then inspect检查 a file called com/android/tools/test_config.properties on the classpath, which is a Java properties file with the following keys:...(省略若干行)
  • 属性:boolean returnDefaultValuesWhether unmocked methods from android.jar should throw exceptions or return default values (i.e. zero or null). See Test Your App for details.
  • 方法:void all(Closure<Test> configClosure)  Configures all unit testing tasks. See Test for available options.
    • Inside the closure闭包、关闭、终止 you can check the name of the task to configure only some test tasks, e.g.
android {
    testOptions {
        unitTests.all {
            if (it.name == 'testDebug') {
                systemProperty 'debug', 'true'
            }
        }
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
String encoding
Java source files encoding.

Boolean incremental
Whether java compilation should use Gradle's new incremental增加的、增量的 model.
This may cause issues in projects that rely on annotation processing etc.

JavaVersion sourceCompatibility 和 targetCompatibility
Language level of the java source code.
Version of the generated Java bytecode.
Similar to what Gradle Java plugin uses. Formats supported are:
"1.6"
1.6
JavaVersion.Version_1_6
"Version_1_6"

2018-7-23