構建-0 Gradle DSL 屬性和方法【API】

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.html

LibraryExtension

The android extension for com.android.library projects.java

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

TestExtension

android extension for com.android.test projects.android

FeatureExtension

The android extension for com.android.feature projects.git

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.
github


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

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

adbOptions { }

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

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
相關文章
相關標籤/搜索