Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Windows 7 Android Studio 2.1.3

Basic Custom Build Basic Build Customization

This ZhangMu

  • Understand Gradle files
  • Introduction to build the tasks
  • Custom build

Understand Gradle files

When you create a new project in Android Studio, three Gradle files are automatically created.

├─ ├─ build.├ ─ Settings.├ ─ build.├ ─ buildCopy the code

Each file has its own purpose

Settings. Gradle file

The Settings file for the new project looks something like this

include ':app'
Copy the code

Gradle creates a Settings object for each Settings file and calls the methods in it.

The top-level build file Indicates The outermost build file

It can configure all modules in the project. The following

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com. Android. Tools. Build: gradle: 2.1.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
Copy the code

The BuildScript code block is where the details are configured, referencing the JCenter repository. In this case, a repository represents a dependent library, in other words, a library file that the app can download and use. JCenter is a well-known Maven repository.

The Dependencies code block configures dependencies. As the comments above indicate, do not add dependencies here, but configure them in a separate module.

Allprojects can be configured for all modules.

Build file in the module

A separate configuration file in the module overwrites the top-level build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.xxx.rust.newproj"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs'.include: ['*.jar'])
    testCompile 'junit: junit: 4.12'
    compile 'com. Android. Support: appcompat - v7:25.1.0'
}
Copy the code

Let’s look at three major code blocks.

plugin

The first line applies the Android application plug-in. The Android plugin is developed and maintained by the Google team. This plug-in provides all the tasks needed to build, test, and package applications and modules.

android

The largest area. The defaultConfig field configates the app core and overrides the configuration in Androidmanifest.xml.

ApplicationId overwrites the package name in the manifest file. But there is a difference between applicationId and package name. The package name in manifest, used in source code and R files. So it makes sense to understand package name as a path to a query class in Android Studio. The applicationId is the unique identifier of an application in the Android system, that is, all application applicationids on an Android device are unique.

dependencies

Is part of Gradle standard configuration. Android is used to configure the library used.

Customizing the build

BuildConfig and resources

Since SDK17, the build tool generates a BuildConfig class that contains the static variable DEBUG and some information. This BuildConfig class is useful if you want to distinguish debug from the official version, such as log. Gradle can extend this class to have more static variables.

Take the NewProj project for example, app\build.gradle

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.xxx.rust.newproj"
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            buildConfigField("String"."BASE_URL"."\"http://www.baidu.com\"")
            buildConfigField("String"."A_CONTENT"."\"debug content\"")
            resValue("string"."str_version"."debug_ver")
        }
        release {
            buildConfigField("String"."BASE_URL"."\"http://www.qq.com\"")
            buildConfigField("String"."A_CONTENT"."\"release content\"")
            resValue("string"."str_version"."release_ver")

            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}Copy the code

BuildConfigField and resValue above can be used in source code after compilation. Note that the escape semicolon above is necessary; Pay attention to case; the arguments passed in here are just as if they were written in code

Below is the BuildConfig file generated after compilation, and you can see that the buildConfigField stuff is already in there

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.xxx.rust.newproj";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Fields from build type: debug
  public static final String A_CONTENT = "debug content";
  public static final String BASE_URL = "http://www.baidu.com";
}
Copy the code

ResValue is added to the resource file

mTv2.setText(R.string.str_version);
Copy the code

Add a way to get applicationId through build.gradle

The attribute applicationId added to the build.gradle module will be compiled into BuildConfig

project.afterEvaluate {
    project.android.applicationVariants.all { variant ->
        def applicationId = [variant.mergedFlavor.applicationId, variant.buildType.applicationIdSuffix].findAll().join()
    }
}
Copy the code

It can be used directly in code

String appID = BuildConfig.APPLICATION_ID;
Copy the code

Method of obtaining time

The build.gradle module adds the method getTime() and the fields in buildTypes.

// Get the current time
static def getTime() {
    String timeNow = new Date().format('YYYYMMdd-HHmmss')
    return timeNow
}

android {
    // ...
    buildTypes {
        debug {
            buildConfigField "String"."BUILD_TIME"."\" " + getTime() + "\" "
        }
        release {
            buildConfigField "String"."BUILD_TIME"."\" " + getTime() + "\" "
            // ...}}}Copy the code

We get the field in buildconfig.java.

  // Fields from build type: debug
  public static final String BUILD_TIME = "20180912-100335";
Copy the code

Method to modify the release APk file name

Gradle version 3.1.4. The method getTime() above is used.

android {
    // ...
    // Change the apK name of release
    applicationVariants.all { variant ->
        variant.outputs.all {
            if (variant.buildType.name == 'release') {
                outputFileName = "xxx_release_${defaultConfig.versionName}_${getTime()}.apk"}}}}Copy the code

The previous method might run into problems: Cannot set the value of read-only property ‘outputFile’ for ApkVariantOutputImpl_Decorated. Reference: stackoverflow.com/questions/4…

Setting of project scope

If there are multiple modules in a project, you can apply the Settings to the entire project without having to modify each module.

NewProj\build.gradle

allprojects {
    repositories {
        jcenter()
    }
}

ext {
    compileSDKVersion = 25
    local = 'Hello from the top-level build'
}
Copy the code

Each build.gradle file can define additional properties in ext code blocks.

In a module’s libModule \build.gradle file, you can reference the ext property of rootProject

android {
    compileSdkVersion rootProject.ext.compileSDKVersion
    buildToolsVersion "25.0.2"
    / /...
}
Copy the code

Project Properties

Where properties are defined

  • Ext code block
  • Gradle. The properties file
  • Command line -p parameter

Project build.gradle file

ext {
    compileSDKVersion = 25
    local = 'Hello from the top-level build'
}

/** * Print properties info */
task aPrintSomeInfo {
    println(local)
    println('project dir: ' + projectDir)
    println(projectPropertiesFileText)
}

task aPrintAllProperites() {
    println('\nthis is aPrintAllProperites task\n')
    Iterator pIt = properties.iterator()
    while (pIt.hasNext()) {
        println(pIt.next())
    }
}
Copy the code

Gradle.properties file

projectPropertiesFileText = Hello there from gradle.properties
Copy the code

Double-click aPrintSomeInfo on the Gradle bar of as to execute the next task

13:08:10: Executing external task 'aPrintSomeInfo'... Hello from the top-level build project dir: G:\openSourceProject\NewProj Hello there from gradle.properties this is aPrintAllProperites task ...... BUILD SUCCESSFUL Total time: 1.025 secS 13:08:11: External Task Execution Finished 'aPrintSomeInfo'Copy the code

Kevin Pelgrims Gradle for Android