Gradle optimization For Android (3) Gradle optimization For Android (3) Gradle optimization For Android (3) Gradle optimization For Android (3) Gradle optimization For Android (4) Like can pay attention to me, not regular summary of the article! Your support is my motivation ha!

Gradle For Android

  • Gradle For Android (1
  • Gradle For Android (2) Multi-channel packaging and signing configuration

Gradle base dependencies, multi-channel packaging, and signature configuration are all covered in the first two Gradle files. Gradle base dependencies, multi-channel packaging, and signature configuration are all covered in the first two Gradle files. Gradle base dependencies, multi-channel packaging, and signature configuration are all covered in the first two Gradle files.


Use placeholders well. Use BuildConfig well. Secure information with easy global Settings

1. Use placeholders wisely

In the last article, when we carried out multi-channel packaging, we said that we could customize apK with different package names according to different channels. Now there is a problem, when we use the third-party platform, we must apply for the appkey according to the package name and signature information, such as typical map development Appkey, amu Appkey, these we need to configure meta-data in the AndroidManifest, such as the following code:

           android:value="dwqirhqifaosfjaofq2dasda" />Copy the code

If this is fixed, of course, will not solve our fundamental problem. Therefore, we need to modify the value dynamically according to the channel. Gradle components provide a nice feature, placeholders, which can be dynamically set in Gradle, for example:

  // In channel configuration...
       xiaomi { // Xiaomi channel
            applicationId 'com.yuan.agradle1'// Personalized customization, mi market package name is different

            // Configure appKey for xiaomi channel
                manifestPlaceholders = [UMENG_CHANNEL_VALUE: 'xiaomi_appkey']
        googlepaly { / / Google play
            applicationId 'com.yuan.agradle2'

            // The GooglePaly channel is configured with appKey
               manifestPlaceholders = [UMENG_CHANNEL_VALUE: 'googlepaly_appkey'        
        }Copy the code

Of course, we can also set once, such as the following:

productFlavors.all { flavor ->
               manifestPlaceholders.put("UMENG_CHANNEL_VALUE"."all_appkey")}Copy the code

Use BuildConfig wisely

BuildConfig is a configuration file that is automatically generated when build.gradle is correctly configured in our module.

package com.yuan.agradle;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.yuan.agradle4";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "baidu";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
}Copy the code

Buildconfig. Java cannot be compiled manually, but it is controlled dynamically by Gradle. Therefore, as an app, Gradle configuration plays an important role. First there are two key fields: 1.buildConfigField 2.resValue. First take a look at the configured code:

  buildTypes {// Indicates that there are two build types: Release DEBUG

            buildConfigField 'String'.'STATE_TEST'.'"debug"'/ildConfigField
            resValue "string"."test_value"."AGradle_debug"//resValue

        release { / / release type
            minifyEnabled false
            // Enable obfuscation
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

            buildConfigField 'String','STATE_TEST','"release"' /ildConfigField
            resValue "string", "test_value", "AGradle_release" //resValue}}Copy the code

BuildConfigField buildConfigField dynamically adds a value of the specified data type to the original buildconfig. Java default based on gradle configuration. Of course, it’s also accessible in the program. Rules of use:

BuildConfigField has three arguments. The first is the data type, which is what type you define the constant value to be, which is the Java equivalent, in this case String. The second parameter is the constant name, in this case STATE_TEST. The third parameter is a constant value. Once defined this way, a constant definition named STATE_TEST is generated in The default configuration generation is:

  buildConfigField 'String'.'STATE_TEST'.'"release"' /ildConfigFieldCopy the code generates a screenshot of:


ResValue buildConfigField mainly changes Java constants, so how do we manage resource files dynamically with Gradle configuration? Yes. Gradle components provide a resValue field that is used to dynamically generate value resources, which can also be accessed in programs. The generated target is generated in generated. XML.

resValue "string"."test_value"."AGradle_release" //resValueCopy the code

Generated. XML screenshot:


Running status: 1. The debug version is running


2. Run the release version


Third, protect information security, convenient global Settings

In the development and compilation process, we need to ensure the security of some sensitive text information as much as possible, such as appkey, signature information, etc. Nowadays, continuous construction is recommended, which eliminates the compilation and packaging work of the program ape. On the one hand, it can make the program ape more focused on development and facilitate testing and debugging. Examples include the current Travis, Jenkins, and other sustainable build environments. For information security, sensitive information such as signature and password is configured by CI service to a large extent, rather than plain text credentials. I will explain CI later, but now I will first describe the global Settings.

Create a global configuration com_cfg.gradle with the following contents:

// Common configuration
ext {
    // android
    BUILD_TOOLS_VERSION  =  "23.0.2"

    //build config
    MIN_SDK_VERSION  =  18
    VERSION_NAME = "1.0"

    // Siging is not recommended
    KEY_ALIAS = 'yuan'
    KEY_PASSWORD = '888888'
    KEY_FILEPATH = ".. /agradle.jks"
    KEY_STORE_PASSWORD = '888888'

    UMENG_CHANNEL_VALUE_XIAOMI =  'xiaomi_appkey'
    UMENG_CHANNEL_VALUE_GOOGLE = 'googlepaly_appkey'
}Copy the code

2. Apply the Gradle configuration in project build.gradle

apply from: 'com_cfg.gradle'Copy the code

Application build.gradle uses custom constants in Ext, for example:

CompileSdkVersion BUILD_SDK_VERSION //SDK build version buildToolsVersion BUILD_TOOLS_VERSION buildTool defaultConfig { ApplicationId "com.yuan.agradle" // Configuration package name minSdkVersion MIN_SDK_VERSION // Minimum SDK version targetSdkVersion TARGT_SDK_VERSION // Target SDK version versionCode VERSION_CODE / / version number versionName VERSION_NAME testInstrumentationRunner / / version name "" }Copy the code

Ci server is in the same mode, using the terminal command line to replace the defined constants in Gradle. If there are multiple Application Modules in a project, this global configuration can achieve the effect of changing more applications. Of course, if you have some Library Modules that you want to publish to JCenter, you can define a library-specific configuration file. Just apply in the Library. This can be configured independently. Not only will it not make its module more cumbersome, but the configuration will be clearer!


This is similar to the third gradle that uses global gradle. The difference is that global Gradle defines ext, while provides configuration parameters directly. But the usage is a little bit go ahead, here’s an example:

1. Create and write some configuration parameters

// android
BUILD_TOOLS_VERSION  =  23.02.//build config
VERSION_NAME = 1.0Copy the code

2. Module usage and precautions

    Compiled versions / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

    compileSdkVersion BUILD_SDK_VERSION as int //SDK compiled version
    buildToolsVersion  BUILD_TOOLS_VERSION// buildTool version corresponds to buildTool

    / / / / / compile configuration / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /

    defaultConfig {
        applicationId "com.yuan.agradle" // Configure the package name
        minSdkVersion MIN_SDK_VERSION as int // Minimum SUPPORTED SDK version
        targetSdkVersion  TARGT_SDK_VERSION as int// Target SDK version
        versionCode VERSION_CODE as int/ / version number
        versionName  VERSION_NAME // Version name

        testInstrumentationRunner ""

    }Copy the code

The configuration is a string. If the constant is an integer, we have to type it as int

5. Common Configurations

1, dexOptions

At dex Gradle may encounter memory use, error information about Java. Lang. OutOfMemoryError: GC overhead limit is exceeded. In this case, you only need to set the javaMaxHeapSize of dexOptions:

dexOptions {  javaMaxHeapSize "2g" }Copy the code

2, Java Compilation Options

Specifies the JDK version that affects all tasks compiling Java source code

android {
        compileOptions {
            sourceCompatibility = "1.7" //JavaVersion.VERSION_1_7
            targetCompatibility = "1.7" //JavaVersion.VERSION_1_7}}Copy the code

Aapt options affects all tasks that use AAPT

android { aaptOptions { noCompress 'foo', 'bar' ignoreAssetsPattern "! .svn:! .git:! .ds_store:! *.scc:.*:Copy the code_ * :! CVS:! thumbs.db:! picasa.ini:! * ~ "}}Copy the code

4, lintOptions

Lint checks when buid is generated, and any errors or warnings will terminate the build, controllable.

lintOptions {
    abortOnError false
}Copy the code

Hope to help some developers ~ specific view can be github demo, also welcome to join the development exchange group ha, details see personal profile. The next article is a confusing explanation of Gradle


Gradle optimization For Android

I write to you as you struggle on your way of growing up