构建配置 概述 Configure your build


Configure your build

The Android build system compiles app resources and source code, and packages them into APKs that you can test, deploy部署, sign签署, and distribute分发. Android Studio uses Gradle, an advanced build toolkit工具包, to automate自动化执行 and manage the build process, while同时 allowing you to define flexible灵活的 custom build configurations. Each build configuration can define its own set of code and resources, while同时 reusing复用 the parts common共有的 to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes流程 and configurable可配置 settings that are specific to building and testing Android applications. 共同提供专用于构建和测试 Android 应用的流程和可配置设置

Gradle and the Android plugin run independent of Android Studio. This means that you can build your Android apps from within Android Studio, the command line on your machine, or on machines where Android Studio is not installed (such as continuous持续性 integration servers). If you are not using Android Studio, you can learn how to build and run your app from the command line. The output of the build is the same whether you are building a project from the command line, on a remote machine, or using Android Studio.
Note: Because Gradle and the Android plugin run independently from Android Studio, you need to update the build tools separately单独. Read the release版本 notes to learn how to update Gradle and the Android plugin.
1
1
 
1
Note: Because Gradle and the Android plugin run independently from Android Studio, you need to update the build tools separately单独. Read the release版本 notes to learn how to update Gradle and the Android plugin.

The flexibility of the Android build system enables you to perform执行 custom build configurations without modifying your app's core source files. This section helps you understand how the Android build system works, and how it can help you customize自定义 and automate multiple build configurations. If you simply want to learn more about deploying部署 your app, see Building and Running from Android Studio. To start creating custom build configurations right away using Android Studio, see Configuring Build Variants.

The build process 流程

The build process involves涉及 many tools and processes that convert转换 your project into an Android Application Package (APK). The build process is very flexible灵活, so it's useful to understand some of what is happening under the hood底层工作原理.
Figure 1. The build process of a typical典型 Android app module.

The build process for a typical Android app module, as shown in figure 1, follows依循 these general steps:
  • The compilers convert your source code into DEX (Dalvik Executable) files, which include the bytecode that runs on Android devices, and everything else into compiled resources.
  • The APK Packager combines the DEX files and compiled resources into a single APK. Before your app can be installed and deployed onto an Android device, however, the APK must be signed.
  • The APK Packager signs your APK using either the debug or release keystore:
    • If you are building a debug version of your app, that is, an app you intend打算、意图 only for testing and profiling分析, the packager signs your app with the debug keystore. Android Studio automatically configures new projects with a debug keystore.
    • If you are building a release version of your app that you intend to release externally向外发布, the packager signs your app with the release keystore. To create a release keystore, read about signing your app in Android Studio.
  • Before generating your final APK, the packager uses the zipalign tool to optimize your app to use less memory when running on a device.
At the end of the build process, you have either a debug APK or release APK of your app that you can use to deploy, test, or release to external users.

Custom build configurations

Gradle and the Android plugin help you configure the following aspects方面 of your build:

Build Types
Build types define certain某些 properties that Gradle uses when building and packaging your app, and are typically通常 configured for different stages阶段 of your development lifecycle. For example, the debug build type enables debug options选项 and signs the APK with the debug key, while the release build type may shrink可压缩, obfuscate混淆, and sign your APK with a release key for distribution进行分发. You must define at least one build type in order to build your app—Android Studio creates the debug and release build types by default. To start customizing packaging settings for your app, learn how to Configure Build Types.

Product Flavors
Product flavors represent代表 different versions of your app that you may release to users, such as free and paid versions of your app. You can customize product flavors to use different code and resources, while sharing and reusing the parts that are common to all versions of your app. Product flavors are optional and you must create them manually手动. To start creating different versions of your app, learn how to Configure Product Flavors.

Build Variants
A build variant is a cross product交叉产物 of a build type and product flavor, and is the configuration Gradle uses to build your app. Using build variants, you can build the debug version of your product flavors during development, or signed release versions of your product flavors for distribution. Although you do not configure build variants directly, you do configure the build types and product flavors that form them. Creating additional build types or product flavors also creates additional build variants. To learn how to create and manage build variants, read the Configure Build Variants overview.

Manifest Entries
You can specify values for some properties of the manifest file in the build variant configuration为构建变体配置中清单文件的一些属性指定值. These build values override the existing values in the manifest file. This is useful if you want to generate multiple APKs for your modules where each of the apk files has a different application name, minimum SDK version, or target SDK version. When multiple manifests are present, Gradle merges manifest settings.

Dependencies
The build system manages project dependencies from your local filesystem and from remote repositories远程资源. This prevents避免 you from having to manually search, download, and copy binary packages of your dependencies into your project directory. To find out more, see Add Build Dependencies.

Signing
The build system enables you to specify signing settings in the build configuration, and it can automatically sign your APKs during the build process. The build system signs the debug version with a default key and certificate签署 using known credentials 证书 to avoid a password prompt提示 at build time. The build system does not sign the release version unless you explicitly define a signing configuration for this build. If you do not have a release key, you can generate one as described描述 in Sign Your App.

ProGuard
The build system enables you to specify a different ProGuard rules file for each build variant. The build system can run ProGuard to shrink and obfuscate your classes during the build process.

Multiple APK Support
The build system enables you to automatically build different APKs that each contain only the code and resources needed for a specific screen density特定屏幕密度 or Application Binary Interface应用二进制界面(ABI). For more information see Build multiple APKs.

Build configuration files

Creating custom build configurations requires you to make changes to one or more build configuration files, or build.gradle files. These plain text纯文本 files use Domain Specific Language域特定语言 (DSL) to describe and manipulate操作 the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don’t need to know Groovy to start configuring your build because the Android plugin for Gradle introduces引入 most of the DSL elements you need. To learn more about the Android plugin DSL, read the DSL reference documentation.

When starting a new project, Android Studio automatically creates some of these files for you, as shown in figure 2, and populates填充 them based on sensible合理的 defaults.
Figure 2. The default project structure for an Android app module.

There are a few Gradle build configuration files that are a part of the standard project structure for an Android app. Before you can start configuring your build, it is important to understand the scope范围 and purpose of each of these files, and the basic DSL elements they should define.

The Gradle settings file

The settings.gradle file, located in the root project directory, tells Gradle which modules it should include when building your app. For most projects, the file is simple and only includes the following:
include ‘:app’
1
1
 
1
include :app’
However, multi-module projects need to specify each module that should go into the final build.

The top-level build file

The top-level build.gradle file, located in the root project directory, defines build configurations that apply to all modules in your project. By default, the top-level build file uses the buildscript block to define the Gradle repositories and dependencies that are common to all modules in the project. The following code sample describes the default settings and DSL elements you can find in the top-level build.gradle after creating a new project.
/** The buildscript block is where you configure the repositories and dependencies for Gradle itself—meaning, you should not include dependencies for your modules here. For example, this block includes the Android plugin for Gradle as a dependency because it provides the additional instructions其他说明 Gradle needs to build Android app modules. */
buildscript {

/** The repositories存储库 block configures the repositories Gradle uses to search or download the dependencies. Gradle pre-configures support for remote repositories such as 【JCenter, Maven Central, and Ivy】. You can also use local repositories or define your own remote repositories. The code below defines JCenter as the repository Gradle should use to look for its dependencies. New projects created using Android Studio 3.0 and higher also include Google's Maven repository. */
    repositories {
        google()
        jcenter()
    }

/** The dependencies block configures the dependencies Gradle needs to use to build your project. The following line adds Android plugin for Gradle version 3.1.0 as a classpath dependency路径依赖. */
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
    }
}

/** The allprojects block is where you configure the repositories and dependencies used by all modules in your project, such as third-party plugins or libraries. However, you should configure module-specific dependencies in each module-level build.gradle file. For new projects, Android Studio includes JCenter and Google's Maven repository by default, but it does not configure any dependencies (unless you select a template that requires some). */
allprojects {
  repositories {
      google()
      jcenter()
  }
}
22
22
 
1
/** The buildscript block is where you configure the repositories and dependencies for Gradle itself—meaning, you should not include dependencies for your modules here. For example, this block includes the Android plugin for Gradle as a dependency because it provides the additional instructions其他说明 Gradle needs to build Android app modules. */
2
buildscript {
3
4
/** The repositories存储库 block configures the repositories Gradle uses to search or download the dependencies. Gradle pre-configures support for remote repositories such as 【JCenter, Maven Central, and Ivy】. You can also use local repositories or define your own remote repositories. The code below defines JCenter as the repository Gradle should use to look for its dependencies. New projects created using Android Studio 3.0 and higher also include Google's Maven repository. */
5
    repositories {
6
        google()
7
        jcenter()
8
    }
9
10
/** The dependencies block configures the dependencies Gradle needs to use to build your project. The following line adds Android plugin for Gradle version 3.1.0 as a classpath dependency路径依赖. */
11
    dependencies {
12
        classpath 'com.android.tools.build:gradle:3.1.0'
13
    }
14
}
15
16
/** The allprojects block is where you configure the repositories and dependencies used by all modules in your project, such as third-party plugins or libraries. However, you should configure module-specific dependencies in each module-level build.gradle file. For new projects, Android Studio includes JCenter and Google's Maven repository by default, but it does not configure any dependencies (unless you select a template that requires some). */
17
allprojects {
18
  repositories {
19
      google()
20
      jcenter()
21
  }
22
}

Configure project-wide properties

For Android projects that include multiple modules, it may be useful to define certain properties at the project level and share them across all the modules. You can do this by adding extra properties to the ext block in the top-level build.gradle file.
buildscript {...}

allprojects {...}

// This block encapsulates封装 custom properties and makes them available to all modules in the project.
ext {
    // The following are only a few examples of the types of properties you can define.
    compileSdkVersion = 26
    // You can also create properties to specify versions for dependencies指定依赖项的版本.
    // Having consistent一致的 versions between modules can avoid conflicts with behavior.
    supportLibVersion = "27.1.1"
    ...
}
1
buildscript {...}
2
3
allprojects {...}
4
5
// This block encapsulates封装 custom properties and makes them available to all modules in the project.
6
ext {
7
    // The following are only a few examples of the types of properties you can define.
8
    compileSdkVersion = 26
9
    // You can also create properties to specify versions for dependencies指定依赖项的版本.
10
    // Having consistent一致的 versions between modules can avoid conflicts with behavior.
11
    supportLibVersion = "27.1.1"
12
    ...
13
}

To access these properties from a module in the same project, use the following syntax句法 in the module's build.gradle file (you can learn more about this file in the section below).
android {
  // Use the following syntax to access properties you defined at the project level: rootProject.ext.property_name
  compileSdkVersion rootProject.ext.compileSdkVersion 
}

dependencies {
    compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
}
8
8
 
1
android {
2
  // Use the following syntax to access properties you defined at the project level: rootProject.ext.property_name
3
  compileSdkVersion rootProject.ext.compileSdkVersion 
4
}
5
6
dependencies {
7
    compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
8
}

Note: 
Although Gradle allows you to define project-wide properties at the module level, you should avoid doing so because it causes the modules that share those properties to be coupled被耦合. Module coupling makes it more difficult to later以后 export导出 a module as a stand-alone project为独立项目 and effectively有效地 prevents防止 Gradle from utilizing使用 parallel平行、并行 project execution执行 to speed up加速 multi-module builds.
1
1
 
1
Although Gradle allows you to define project-wide properties at the module level, you should avoid doing so because it causes the modules that share those properties to be coupled被耦合. Module coupling makes it more difficult to later以后 export导出 a module as a stand-alone project为独立项目 and effectively有效地 prevents防止 Gradle from utilizing使用 parallel平行、并行 project execution执行 to speed up加速 multi-module builds.

The module-level build file

The module-level build.gradle file, located in each project/module/ directory, allows you to configure build settings for the specific module it is located in. Configuring these build settings allows you to provide custom packaging options打包选项, such as additional build types and product flavors, and override覆盖 settings in the main/ app manifest or top-level build.gradle file.

This sample Android app module build.gradle file outlines概述 some of the basic DSL elements and settings that you should know.

/** The first line in the build configuration applies the Android plugin for Gradle to this build【将Gradle的Android插件应用于此构建】 and makes the android block available to specify Android-specific build options. */
apply plugin: 'com.android.application'

/** The android block is where you configure all your Android-specific build options. */
android {
    
/** compileSdkVersion specifies the Android API level Gradle should use to compile your app. This means your app can use the API features included in this API level and lower. */
  compileSdkVersion 26

/** buildToolsVersion specifies the version of the SDK build tools, command-line utilities命令行实用程序, and compiler that Gradle should use to build your app. You need to download the build tools using the SDK Manager. If you're using Android plugin 3.0.0 or higher, this property is optional— the plugin uses a recommended推荐的 version of the build tools by default. */
  buildToolsVersion "27.0.3"

/** The defaultConfig block encapsulates包囊 default settings and entries项、条目 for all 【build variants】, and can override some attributes in main/AndroidManifest.xml dynamically动态地 from the build system. You can configure 【product flavors】 to override these values for different versions of your app.  */
  defaultConfig {
      
/** applicationId uniquely identifies唯一标识 the package for publishing. However, your source code should 【still reference the package name】 defined by the package attribute in the main/AndroidManifest.xml file. */
    applicationId 'com.example.myapp'
        
    minSdkVersion 15  // Defines the minimum API level required to run the app.
    targetSdkVersion 26  // Specifies the API level used to 【test】 the app. 
    versionCode 1 // Defines the version number of your app.
    versionName "1.0"  // Defines a 【user-friendly】用户友好 version name for your app.
  }

/** The buildTypes block is where you can configure multiple build types. By default, the build system defines two build types: debug and release. The debug build type is not explicitly明确地 shown in the default build configuration, but it includes debugging tools and is signed with the debug key. The release build type applies Proguard settings and is not signed by default. */
  buildTypes {

/** By default, Android Studio configures the release build type to enable code shrinking, using minifyEnabled, and specifies the Proguard settings file. */
    release {
        minifyEnabled true // Enables code shrinking for the release build type.
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }

/** The productFlavors block is where you can configure multiple product flavors. This allows you to create different versions of your app that can override the defaultConfig block with their own settings. Product flavors are optional, and the build system does not create them by default. This example creates a free and paid product flavor. Each product flavor then specifies its own application ID, so that they can exist on the Google Play Store, or an Android device, simultaneously同时. If you're using Android plugin 3.0.0 or higher, you need to also 【declare声明 and assign分配 each flavor to a flavor dimension维度】. To learn more, read the migration移民 guide. */
  productFlavors {
    free {
      applicationId 'com.example.myapp.free'
    }

    paid {
      applicationId 'com.example.myapp.paid'
    }
  }

/** The splits拆分、分裂 block is where you can configure different APK builds that each contain only code and resources for a 【supported screen density or ABI】. You'll also need to configure your build so that each APK has a different versionCode. */
  splits {
    density {  // Settings to build multiple APKs based on screen density.
      enable false  // Enable or disable building multiple APKs.
      exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi" // Exclude排除 these densities when building multiple APKs.
    }
  }
}

/** The dependencies block in the module-level build configuration file only specifies dependencies required to build the module itself. If you're using Android plugin 3.0.0 or higher, you should use the new dependency configurations, which help you improve提高 build speeds by restricting限制 which dependencies leak泄漏 their APIs to other modules. */
dependencies {
    compile project(":lib")
    compile 'com.android.support:appcompat-v7:27.1.1'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
1
/** The first line in the build configuration applies the Android plugin for Gradle to this build【将Gradle的Android插件应用于此构建】 and makes the android block available to specify Android-specific build options. */
2
apply plugin: 'com.android.application'
3
4
/** The android block is where you configure all your Android-specific build options. */
5
android {
6
    
7
/** compileSdkVersion specifies the Android API level Gradle should use to compile your app. This means your app can use the API features included in this API level and lower. */
8
  compileSdkVersion 26
9
10
/** buildToolsVersion specifies the version of the SDK build tools, command-line utilities命令行实用程序, and compiler that Gradle should use to build your app. You need to download the build tools using the SDK Manager. If you're using Android plugin 3.0.0 or higher, this property is optional— the plugin uses a recommended推荐的 version of the build tools by default. */
11
  buildToolsVersion "27.0.3"
12
13
/** The defaultConfig block encapsulates包囊 default settings and entries项、条目 for all 【build variants】, and can override some attributes in main/AndroidManifest.xml dynamically动态地 from the build system. You can configure 【product flavors】 to override these values for different versions of your app.  */
14
  defaultConfig {
15
      
16
/** applicationId uniquely identifies唯一标识 the package for publishing. However, your source code should 【still reference the package name】 defined by the package attribute in the main/AndroidManifest.xml file. */
17
    applicationId 'com.example.myapp'
18
        
19
    minSdkVersion 15  // Defines the minimum API level required to run the app.
20
    targetSdkVersion 26  // Specifies the API level used to 【test】 the app. 
21
    versionCode 1 // Defines the version number of your app.
22
    versionName "1.0"  // Defines a 【user-friendly】用户友好 version name for your app.
23
  }
24
25
/** The buildTypes block is where you can configure multiple build types. By default, the build system defines two build types: debug and release. The debug build type is not explicitly明确地 shown in the default build configuration, but it includes debugging tools and is signed with the debug key. The release build type applies Proguard settings and is not signed by default. */
26
  buildTypes {
27
28
/** By default, Android Studio configures the release build type to enable code shrinking, using minifyEnabled, and specifies the Proguard settings file. */
29
    release {
30
        minifyEnabled true // Enables code shrinking for the release build type.
31
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
32
    }
33
  }
34
35
/** The productFlavors block is where you can configure multiple product flavors. This allows you to create different versions of your app that can override the defaultConfig block with their own settings. Product flavors are optional, and the build system does not create them by default. This example creates a free and paid product flavor. Each product flavor then specifies its own application ID, so that they can exist on the Google Play Store, or an Android device, simultaneously同时. If you're using Android plugin 3.0.0 or higher, you need to also 【declare声明 and assign分配 each flavor to a flavor dimension维度】. To learn more, read the migration移民 guide. */
36
  productFlavors {
37
    free {
38
      applicationId 'com.example.myapp.free'
39
    }
40
41
    paid {
42
      applicationId 'com.example.myapp.paid'
43
    }
44
  }
45
46
/** The splits拆分、分裂 block is where you can configure different APK builds that each contain only code and resources for a 【supported screen density or ABI】. You'll also need to configure your build so that each APK has a different versionCode. */
47
  splits {
48
    density {  // Settings to build multiple APKs based on screen density.
49
      enable false  // Enable or disable building multiple APKs.
50
      exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi" // Exclude排除 these densities when building multiple APKs.
51
    }
52
  }
53
}
54
55
/** The dependencies block in the module-level build configuration file only specifies dependencies required to build the module itself. If you're using Android plugin 3.0.0 or higher, you should use the new dependency configurations, which help you improve提高 build speeds by restricting限制 which dependencies leak泄漏 their APIs to other modules. */
56
dependencies {
57
    compile project(":lib")
58
    compile 'com.android.support:appcompat-v7:27.1.1'
59
    compile fileTree(dir: 'libs', include: ['*.jar'])
60
}

Gradle properties files

Gradle also includes two properties files, located in your root project directory, that you can use to specify settings for the Gradle build toolkit itself:
  • gradle.propertiesThis is where you can configure project-wide Gradle settings, such as the Gradle daemon's守护 maximum heap size. For more information, see The Build Environment.
org.gradle.jvmargs=-Xmx1536m
 
1
org.gradle.jvmargs=-Xmx1536m
  • local.propertiesConfigures local environment properties for the build system, such as the path to the SDK installation. Because the content of this file is automatically generated自动生成 by Android Studio and is specific to the local developer environment, you should not modify this file manually or check it into your version control system版本控制系统.
ndk.dir=D\:\\software\\android_sdk\\ndk-bundle
sdk.dir=D\:\\software\\android_sdk
x
1
ndk.dir=D\:\\software\\android_sdk\\ndk-bundle
2
sdk.dir=D\:\\software\\android_sdk

Syncing project with Gradle files

When you make changes to the build configuration files in your project, Android Studio requires要求 that you sync同步 your project files so that it can import your build configuration changes and run some checks to make sure your configuration won't create build errors.

To sync your project files, click Sync Now in the notification bar that appears when you make a change, as shown in figure 3, or click Sync Project  from the menu bar. If Android Studio notices any errors with your configuration, for example, your source code uses API features that are only available in an API level higher than your compileSdkVersion, the Messages window appears to describe the issue.
Figure 3. Syncing the project with build configuration files in Android Studio.

Source sets

Android Studio logically按逻辑关系 groups分组  source code and resources for each module into source sets. A module’s main/ source set includes the code and resources used by all its build variants. Additional其他 source set directories目录 are optional, and Android Studio does not automatically create them for you when you configure new build variants. However, creating source sets, similar to类似于 main/, helps organize files and resources that Gradle should only use when building certain versions of your app:
  • src/main/This source set includes code and resources common共同的 to all build variants.
  • src/buildType/Create this source set to include code and resources only for a specific build type.
  • src/productFlavor/Create this source set to include code and resources only for a specific product flavor.
Note: If you configure your build to combine联合、结合 multiple product flavors, you can create source set directories for each combination组合 of product flavors between the 【flavor dimensions】: src/productFlavor1ProductFlavor2/
 
1
Note: If you configure your build to combine联合、结合 multiple product flavors, you can create source set directories for each combination组合 of product flavors between the 【flavor dimensions】: src/productFlavor1ProductFlavor2/
  • src/productFlavorBuildType/Create this source set to include code and resources only for a specific build variant. For example, to generate the "fullDebug" version of your app, the build system merges code, settings, and resources from following source sets:
    • src/fullDebug/   (the build variant source set)
    • src/debug/   (the build type source set)
    • src/full/   (the product flavor source set)
    • src/main/   (the main source set)

Note: When you create a new file or directory in Android Studio, using the 【File > New】 menu options, you can create it for a specific针对特定的 source set. The source sets you can choose from are based on your build configurations, and Android Studio automatically creates the required directories if they don't already exist.
x
 
1
Note: When you create a new file or directory in Android Studio, using the 【File > New】 menu options, you can create it for a specific针对特定的 source set. The source sets you can choose from are based on your build configurations, and Android Studio automatically creates the required directories if they don't already exist.

If different source sets contain different versions of the same file, Gradle uses the following priority order优先顺序 when deciding决定 which file to use (source sets on the left override the files and settings of source sets to the right):
build variant > build type > product flavor > main source set > library dependencies
1
1
 
1
build variant > build type > product flavor > main source set > library dependencies

This allows Gradle to use files that are specific专用于 to the build variant you are trying to build while同时 reusing复用 activities, application logic应用逻辑, and resources that are common to other versions of your app. When merging multiple manifests, Gradle uses the same priority order, so each build variant can define different components组件 or permissions in the final manifest. To learn more about creating custom source sets, go to Create Source Sets for Build Variants.

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Last updated June 5, 2018.

猜你喜欢

转载自www.cnblogs.com/baiqiantao/p/9343093.html