Gradle is a flexible build plug-in that, when combined with Android Studio, solves many of the problems encountered in the past when developing apps using Eclipse. At the same time, with the scripting nature of Groove, a DSL language, it was obviously difficult to remember the syntax.

In fact, there are not many common usage scenarios for Gradle plugins, and you don’t need to learn all the ways of using Groove by rote. Here is a summary of common Android development Gradle usage scenarios for future reference.

Multi-channel packaging

For one of the most common multichannel usage scenarios, see how Gradle multichannel packaging is used.

Modify the channel name of the umMON statistics in the Manifest file as a reference variable (variable name is optional) :

<meta-data
    android:name="${UMENG_CHANNEL_VALUE}"
    android:value="Channel_ID" />Copy the code

Add the channel name to the productFlavors configuration item of the build.gradle file and set it to the variable names mentioned above:

android {
    productFlavors {
        xiaomi {}
        yingyongbao {}
    }

    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
}Copy the code

Execute the command statement to package the Task:

./gradle assembleReleaseCopy the code

Or targeted only specific channel packages, such as:

./gradle assembleXiaomiReleaseCopy the code

Note: In the Gradle Projects window you can view a list of all Tasks that can be executed. This original packaging method is suitable for scenarios with few channel names. When there are dozens or even hundreds of channels, the packaging time will be relatively long. Other packaging schemes are recommended, such as:

  • packer-ng-plugin

  • Meituan-dianping technical team: Walle, a new generation of open source Android channel package generation tool

Custom output APK file name

You can modify the package output APK file name, add time stamp, compile type, version information and other keywords, apK file is more recognizable, such as:

apply plugin: 'com.android.application' def releaseTime() { return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) } android { android.applicationVariants.all { variant -> variant.outputs.each { output -> output.outputFile = new File(output.outputFile.parent, rootProject.getName() + "-" + buildType.name + "-" + releaseTime() + "-v" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk"); }}}Copy the code

Here you add the project name to the APK file name, or you can use applicationId, etc. The result is as follows:

YFSample - release - 2017-09-12 - v1.0-1. The apkCopy the code

Debug and Release have the same signature

android {
    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "boolean", "DEBUG_MODE", "true"
            signingConfig signingConfigs.config
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "boolean", "DEBUG_MODE", "false"
            signingConfig signingConfigs.config
        }
    }
}Copy the code

This step can be operated through a graphical interface, which is more convenient. Right-click the Project and click Open Module Settings to Open the Project Structure window and set it in the Build Types TAB.

Hiding Signature Information

The signature information is one of the most private parts of a project and is not secure enough to be exposed directly in the build.gradle file. Especially if you need to upload to a hosting platform like GitHub.

It is better to create a new file in the project root directory specifically to store the signature information and add it to the ignore file configuration. The specific operation process is as follows:

First, create a keystore.properties file:

ReleaseKeyPassword=sampleKeyPwd ReleaseKeyAlias=sampleAlias ReleaseStorePassword=sampleStorePwd ReleaseStoreFile=.. /sample.jksCopy the code

The second step is to introduce the signature information in the outermost layer of the build.gradle file:

allprojects {
    afterEvaluate { project ->
        def propsFile = rootProject.file('keystore.properties')
        def configName = 'config'

        if (propsFile.exists() && android.signingConfigs.hasProperty(configName)) {
            def props = new Properties()
            props.load(new FileInputStream(propsFile))
            android.signingConfigs[configName].storeFile = file(props['ReleaseStoreFile'])
            android.signingConfigs[configName].storePassword = props['ReleaseStorePassword']
            android.signingConfigs[configName].keyAlias = props['ReleaseKeyAlias']
            android.signingConfigs[configName].keyPassword = props['ReleaseKeyPassword']
        }
    }
}Copy the code

That’s it. There is also a shortened version of the second step, which can also be used directly:

def keystorePropertiesFile = rootProject.file("keystore.properties"); def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) android {  signingConfigs { config { storeFile file(keystoreProperties['ReleaseStoreFile']) storePassword keystoreProperties['ReleaseStorePassword'] keyAlias keystoreProperties['ReleaseKeyAlias'] keyPassword keystoreProperties['ReleaseKeyPassword'] } } }Copy the code

Of course, there are many other ways to hide signature information. For example, if configured in a local environment variable, or in a build.gradle file, or dynamically reading input from the command line at compile time, the reading method varies depending on the setting.

The log switch

Debug and Release control variables for different compilation modes are defined in app/build.gradle. Variable names can be changed as you like:

buildTypes {
    debug {
        buildConfigField "boolean", "DEBUG_MODE", "true"
    }
    release {
        buildConfigField "boolean", "DEBUG_MODE", "false"
    }
}Copy the code

After recompilation, the automatically generated BuildConfig class contains the DEBUG_MODE property defined above and can be used.

Log switch for more solutions, see: Android can be used as a Log switch some operations and security.

Environmental separation

It is also a common scenario to use both the test server and the production server in development. How to install and configure the debug package of the test environment and the release package of the production environment in the same device is also a problem to be faced. Check out my article:

Android uses Gradle to achieve app environment separation

Refer to the link

Learn more about Android, Gradle, and Groove. In addition to visiting Gradle’s official website, we recommend you read these articles:

  • InfoQ – In-depth Understanding of Android I: Gradle details

  • GitBook – Gradle User Guide

  • Geek Academy – How to use Gradle

END

About me: Yifeng, blog address: Yifeng. Studio /, Sina Weibo: IT Yifeng

Scan the QR code on wechat, welcome to follow my personal public account: Android Notexia

Not only share my original technical articles, but also the programmer’s workplace reverie