Gradle

What is Gradle?

Gradle is a project automation tool that declares project Settings based on the Groovy Language and supports the Kotlin file xxx.gradle. KTS as a Domain Specified Language (DSL).

2. Compare other build tools

The most direct comparisons are between Gradle and Maven, as well as Ant, but there are very few projects built on Ant right now. First, Gradle’s simplicity is much better than Maven’s. The Groovy syntax is much easier to write and read than Xml in Maven. Second, customization is much easier in Gradle than in Maven. You can customize tasks in Gradle and write plugins in Maven.

3. Gradle installation and configuration

Install, configure environment variables, and test the installation results. For details, see Gradle’s website gradle.org/install/

Gradle project directory structure

1. Basic Gradle project

Create a build.gradle file and run the gradle build command to generate the. Gradle hidden file. This is the basic Gradle project.



gradle wrapper






Android Studio gradle directory structure

We need a little bit here. In Android Studio, Gradle and Android run independently, which means that Android builds independently of the IDE and can work with Gradle to build projects independently. Android Studio simply helps us generate a directory structure and interface the tasks in Gradle. Let’s take a look at the directory structure of the new AndorID project


Build configuration file explanation

1, Settings. Gradle

This is a gradle setup file, located at the root of your project, that configures the multi-module build of your project, including ‘:app’, ‘:example_module’, using app modules, example_module modules in the same directory. You can also specify the module path. Use the following

include ':app'
include ':example_module'
project(':example_module').projectDir = new File(rootDir,'example/example_module')
Copy the code


Gradle. properties, local.properties

This file is a project properties file that can be used to hold key-value resources for use by the project. Gradle. Jvmargs = -xmx1536m. This property is the maximum heap size of gradle daemon processes. We can also customize the value org.gradle.jvmargs = -xmx2048m. You can also configure other properties such as org.gradle.Caching =true to allow gralde configuration to use caching to reduce compilation time. There are also a lot of properties can be Build in the configuration specific can see Gradle website Environmentdocs.gradle.org/current/use… The local SDK and NDK paths are specified in local.properties, and.gitignore is required for multi-user development.

3. Build. Gradle

The project-level build.gradle file is located at the project root and is used to define build configurations that apply to all modules in the project.

/** * buildscript{} declare dependencies needed by the project, such as plugins that need to be referenced in the module * for example, to reference apply in the module:'com.android.application'* You need to add the dependency CLASspath here'com. Android. Tools. Build: gradle: 3.1.4'*/ buildscript {/** * repositories{} is the repository for gradle, which contains Google () and maven ()'https://maven.google.com/'} */ repositories {Google () jCenter ()} Use the form [group]:[name]:[version] */ dependencies {classpath'com. Android. Tools. Build: gradle: 3.1.4'}} /** * Allprojects {repositories} defines the configuration of all modules in the project ** * AllProjects {repositories} Google () jCenter ()}} /** * Here is a Gradle task named clean, * using Groovy language, fully compatible with Java, * can follow the delete method, */ Task clean(type: Delete) {
    delete rootProject.buildDir
}

Copy the code

Build. Gradle in module

The module-level build.gradle file is located in each Module folder and is used to configure build Settings applicable to the module in which it is located, such as custom packaging Settings, importing dependencies within the module, and so on.

Com.android. application * provides the availability of the Android {} configuration. Users build Android projects */ apply plugin:'com.android.application'/** * android{} is a property configured according to com.android.application. Android {/** * compileSdkVersion is the build version in Gradle, * You can use this version and the following API features * * buildToolsVersion Version of the Android SDK buildTools */ compileSdkVersion 26 buildToolsVersion"28.0.3"/** * Basic configuration, some configuration overrides the configuration */ defaultConfig {/** * applicationId, which will be overridden in the manifest when compiled and packaged'com.example.myapp'// Define the minimum running Android version minSdkVersion 15 // specify the API level of the application for testing. TargetSdkVersion 26 // app version number. The app installed on some mobile phones will be verified and cannot be degraded versionCode 1 // app versionName. Generally, the three-digit control "1.1.0" versionName is used"1.0"} /** * buildTypes {} declares buildTypes, including debug by default, release * can also add custom buildTypes */ buildTypes {/** * configure options when build type is release, such as whether to enable obliquation, And obfuscation rule files * can also add build configuration, such as add signature file related configuration */ release {minifyEnabledtrue
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'} /** * productFlavors {} declarations of different flavors. * The configuration can override the configuration in defaultConfig {} * for example, here is an example of configuring a paid version and a free version * Using different ApplicationIDS so that both projects can run on the same phone */ productFlavors { free { applicationId'com.example.myapp.free'
    }

    paid {
      applicationId 'com.example.myapp.paid'}} /** * Multiple APK build, according to the screen DPI or system ABI to generate different APK * use less, // That window has a split Settings density {//disable the density split mechanism
      enable false

      // Exclude these densities from splits
      exclude "ldpi"."tvdpi"."xxxhdpi"."400dpi"."560dpi"}} /** * dependencies {/** * dependencies {/":lib")
    implementation 'com. Android. Support: appcompat - v7:28.0.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])}Copy the code

Suggestions for improving compilation speed

1. Use the latest Android Gradle plugin

The Google Tools Team has been working on improving the build speed of Android Studio with the latest gradle Plugin. After android Gradle Plugin 3.0.0, Google has introduced a new dependency method. And forced to abandon the old dependency method, the original compile closure method, separated into implementation, API to clarify the dependencies of the project. Where implementation is only valid for the current module dependency, API and compile, there is dependency transitivity. Incorrect use can cause the dependency to be loaded twice, increasing the compile time. After more 3.0.0 features can refer to the official document of the Dependency part configurations developer.android.com/studio/buil…

    - compile 'com. Android. Support: appcompat - v7:27.1.1'
    + implementation 'com. Android. Support: appcompat - v7:27.1.1'

Copy the code

2. Avoid using Multidex

When minSdkVersion is below 21 (excluding 21), the compile time increases significantly. We can improve the development efficiency by compiling minSdkVersion 21 as the customized development version. The specific configuration is as follows:

android {
    defaultConfig {
        ...
        multiDexEnabled true
    }
    productFlavors {
        dev {
            minSdkVersion 21
        }
        prod {
            minSdkVersion your_minSDKVersion
        }
    }
	...
}

Copy the code

3. Avoid multi-APK (not used often)

This method can be used when spilts{} is used to generate different APKs for projects that require support for different ABI or DPI. The splits will be closed during the development and commissioning. The specific configurations are as follows:

android {
	...
   if(project. HasProperty (' devBuild)) {splits. Abi. Enable =false
      splits.density.enable = false}... }Copy the code

Use this command when using the command line build:

	./gradlew assembleDevelopmentDebug -PdevBuild
	// gradlew assembleDevelopmentDebug -PdevBuild
Copy the code

When using Android Studio to Build, you can do the following configuration: Open the Preferences -> Build, Execution, Deployment -> Compiler, and then enter the -pDevBuild Command line option, as shown in the figure below:

Reduce the number of packaged resource files

During debugging, it is not necessary to compile all resource files. Usually, only one resource file is selected to reduce compilation time. The specific configuration is as follows:

android{ ... productFlavors { development { minSdkVersion 21 //only package english translations, And xxhdpi resources resConfigs (" en ", "xxhdpi")}}... }Copy the code

5. Disable PNG compression

PNG compression is enabled by default when Android is built. During development and debugging, PNG compression can be disabled as follows:

android {
	...
	if(project. HasProperty (' devBuild)) {aaptOptions cruncherEnabled =false}... }Copy the code

6. Use Instant Run

Instant Run has been greatly optimized since Android Studio 3.0, and the previous version had updated code that didn’t run on the phone, so it was turned off. You can try it now.

Do not define dynamic variables in Gradle

Do not use dynamic definitions in development debugging situations

// def buildDateTime = new Date().format(' yyMMddHHmm ').tointeger () def buildDateTime = project.hasProperty(' devBuild ')?  100: new Date().format(' yyMMddHHmm ').tointeger () Android {defaultConfig {versionCode buildDateTime}}Copy the code

8. Do not use dynamically dependent versions

The project is uncertain in the construction process, which may take too long or fail to compile due to network problems. Gradle checks for new dependency versions every 24 hours to increase dependency resolution time. Do not use the following dependencies

// Wrong demonstration implementation'com.appadhoc:abtest:latest'
	implementation 'com.android.support:appcompat-v7:27+'

Copy the code

Gradle daemons allocate the maximum heap size

Allocate more memory may be on the construction of large projects have time decreases, specific also look at other factors such as the computer configuration, specific can consult gradle website you JVM memory:docs.gradle.org/current/use… Gradle.properties is configured when the new version is configured

	org.gradle.jvmargs=-Xmx1536m

Copy the code

Do not configure in build.gradle using older versions

DexOptions {javaMaxHeapSize = '4g'}Copy the code

10. Use Gradle cache

Gradle caching is a new feature in Gradle 3.5. When caching is enabled, Gradle reuses the results of a previous build. Add the following configuration to gradle.properties:

	org.gradle.caching=true

Copy the code

The above points are from Google I/O 2017, which can be found in the video www.youtube.com/watch?v=7ll…

11. Specifically optimize the construction time of the project

As for the construction of each project, the specific optimization will not be the same. We can output the specific construction time of our project into a document to analyze which part of the construction time is too long for targeted optimization. Specific commands are as follows:

	gradlew --profile --recompile-scripts --offline --rerun-tasks assembleFlavorDebug
Copy the code
  • –profile: Enable analysis
  • –recompile-scripts: Forces recompilation of scripts when caching is bypassed.
  • –offline: Disables Gradle from extracting online dependencies. This ensures that any delay caused by Gradle trying to update dependencies does not interfere with your analysis data. You should have built your project once to ensure that Gradle has downloaded and cached your dependencies.
  • Rerun-tasks: Forces Gradle to rerun all tasks and ignore any task optimizations. After the build is complete, use a browser to open the generated profile- in the _project-root_/build/reports/profile/ directorytimestamp.html to see the specific build time report.

Five, the summary

From the above article, we have seen how to configure Gradle to build Android projects, and how to optimize the part of the project build. However, we still know little about the principle, such as why we can define android{} in build.gradle. In the spirit of knowing why it is possible to configure a project here, we will continue to explore Gradle, learn about groovy syntax, learn about Tasks in Gradle, and use custom build functionality. Related links to Android Gradle play with custom features

Reference documents: official document of android configuration build developer.android.com/studio/buil… Gradle official documents – Building Android Apps guides.gradle.org/building-an… Google I/O mentioned in speed up the compilation of Android studio a few Suggestions blog.csdn.net/sd19871122/…

Pay attention to wechat public number, the latest technology dry goods real-time push