Android Plugin DSL Reference
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. |
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 | |
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
}
}
buildTypes {
release {
debuggable false
}
debug {
}
pre {
initWith release
debuggable true
}
}
属性
dependencies {
freeWearApp project(:wear:free') // applies to variant using the free flavor
wearApp project(':wear:base') // applies to all other variants
}
dependencies {
freeWearApp project(:wear:free') // applies to variant using the free flavor
wearApp project(':wear:base') // applies to all other variants
}
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
project :app
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
project :app
// 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']
}
}
}
// 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']
}
}
}
com/example/MyClass.class
com/example/MyClass.class
-
proguard-android.txt
-
proguard-android-optimize.txt
android {
buildTypes {
debug {
pseudoLocalesEnabled true
}
}
}
android {
buildTypes {
debug {
pseudoLocalesEnabled true
}
}
}
android {
jacoco {
version = '0.6.2.201302030002'
}
}
android {
jacoco {
version = '0.6.2.201302030002'
}
}
方法
buildConfigField "boolean", "isHongkongUser", "true"
buildConfigField "int", "countryCode", "20094"
buildConfigField "String", "BASE_URL", '"http://110.com/"'
buildConfigField "boolean", "isHongkongUser", "true"
buildConfigField "int", "countryCode", "20094"
buildConfigField "String", "BASE_URL", '"http://110.com/"'
-
proguard-android.txt
-
proguard-android-optimize.txt
脚本块
postprocessing {
}
postprocessing {
}
productFlavors 和 defaultConfig
productFlavors {
productA {
}
productB {
}
productFlavors.all {
}
android.applicationVariants.all { variant ->
variant.outputs.all { output ->
variant.productFlavors.each { flavor ->
...
}
}
}
}
productFlavors {
productA {
}
productB {
}
productFlavors.all {
}
android.applicationVariants.all { variant ->
variant.outputs.all { output ->
variant.productFlavors.each { flavor ->
...
}
}
}
}
属性
-
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
-
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...".
方法
- 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)
-
void maxSdkVersion(int maxSdkVersion)
-
void minSdkVersion(int minSdkVersion)
-
void minSdkVersion(String minSdkVersion)
-
void targetSdkVersion(int targetSdkVersion)
-
void targetSdkVersion(String targetSdkVersion)
-
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)
testInstrumentationRunnerArgument "size", "medium"
testInstrumentationRunnerArgument "size", "medium"
./gradlew connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.size=medium
./gradlew connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.size=medium
-
void missingDimensionStrategy(String dimension, String requestedValue)
-
void missingDimensionStrategy(String dimension, String... requestedValues)
- void missingDimensionStrategy(String dimension, List<String> requestedValues)
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
project :app
Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
project :app
// 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 {}
}
}
// 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
android {
defaultConfig {
ndk {
abiFilters 'x86', 'x86_64', 'armeabi' // Tells Gradle to build outputs for the following ABIs and package them into your APK.
}
}
}
android {
defaultConfig {
ndk {
abiFilters 'x86', 'x86_64', 'armeabi' // Tells Gradle to build outputs for the following ABIs and package them into your APK.
}
}
}
- armeabi:第5代、第6代的ARM处理器,早期的手机用的比較多。
-
armeabiv-v7a:第7代及以上的 ARM 处理器。2011年15月以后的生产的大部分Android设备都使用它.
- arm64-v8a:第8代、64位ARM处理器,非常少设备,三星 Galaxy S6是当中之中的一个。
-
x86:平板、模拟器用得比較多。
-
x86_64:64位的平板。
- mips
- mips64
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
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'
}
}
}
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
-
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 name:A concise name for the source directory (typically used to identify it in a collection).
-
属性:File srcFile:The file.
-
方法:AndroidSourceFile srcFile(Object srcPath):Sets the location of the file. Returns this object.
AndroidSourceDirectorySet
-
PatternFilterable filter:The filter used to select the source from the source directories.
-
String name:A concise name for the source directory (typically used to identify it in a collection).
-
FileTree sourceFiles:The list of source files as a FileTree
-
Set<File> srcDirs:The 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
-
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.
- Note: Building per-language APKs is supported only when building configuration APKs for Android Instant Apps.
-
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.
脚本块
abi { }
density { }
language { }
abi { }
density { }
language { }
AbiSplitOptions 和 DensitySplitOptions
-
Set<String> applicableFilters:Returns 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 enable:Whether to split in this dimension.
-
boolean universalApk:Whether to create an FULL_APK with all available ABIs.
-
boolean auto:Whether 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> compatibleScreens:A 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
-
属性: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.
}
}
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> additionalParameters:List of additional parameters to be passed to dx.
-
String javaMaxHeapSize:Specifies the -Xmx value when calling dx. Example value is "2048m".
-
boolean jumboMode:Enable jumbo巨大的、庞然大物的 mode in dx (--force-jumbo).
-
boolean keepRuntimeAnnotatedClasses:Keep 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 maxProcessCount:The 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 preDexLibraries:Whether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.
- Integer threadCount:Number 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.
}
}
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'
}
}
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 { }
unitTests { }
UnitTestOptions
-
属性:boolean includeAndroidResources:Enables 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 returnDefaultValues:Whether 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'
}
}
}
}
android {
testOptions {
unitTests.all {
if (it.name == 'testDebug') {
systemProperty 'debug', 'true'
}
}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
"1.6"
1.6
JavaVersion.Version_1_6
"Version_1_6"
"1.6"
1.6
JavaVersion.Version_1_6
"Version_1_6"