Android Gradle

Android Gradle

Android Gradle

Customize Android Gradle project

1. DefaultConfig Default configuration

DefaultConfig is the default configuration, which is a ProductFlavour. For multi-channel packaging, etc., defaultConfig is used by default if a ProductFlavour is not configured separately for customization

ApplicationId (1)

Specifies the generated app package name. The value is String, for example: applicationId “com.android.xx”

(2) the minSdkVersion

The lowest supported Android OS version of the App, the corresponding value is int (that is, the ApiLevel of the SDK), for example, minSdkVersion 25

(3) the targetSdkVersion

The optional value is the same as minSdkVersion

(4) versionCode

Internal version number, the corresponding value is int, which is used to configure the internal version number of the Android App. It is usually used for version upgrade

(5) versionName

Used to configure the app version name, the corresponding value is String, such as “v1.0.0”, let the user know the current app version. VersionCode is for internal use, and versionName is for external use. Together, the version upgrade control of app is completed.

(6) testApplicationId

Set the package name of the test app. The default package name is applicationId + “.test”.

(7) testInstrumentationRunner

Used to configure the unit test is used when the Runner, the default android. Test. InstrumentationTestRunner.

SigningConfig (8)

Configure the default signature information to sign the generated APP. The corresponding value is the SigningConfig object. For details, see configuring signature information.

(9) proguardFile and proguardFiles

Both are configuration obfuscation rule files. The difference is that proguardFile accepts one file object, while proguardFiles can accept multiple files at the same time.

MultiDexEnabled (10)

Whether to enable the function of automatically splitting multiple Dex, which is used to break the setting when the method exceeds 65535

multiDexEnabled true

2. Configure signature information

Android Gradle provides signingConfigs {} configuration block is used to generate multiple signature configuration information, its type is NamedDomainObjectContainer, therefore, All we define in signingConfigs{} is an object instance of SigningConfig.

A SigningConfig, or signature configuration, can be configured with the following elements: storeFile: signature file location; StoreType: type of the signature certificate (optional). StorePassword: indicates the password of the signature certificate. KeyAlias: indicates the keyAlias of the signing certificate. KeyPassword: indicates the keyPassword in the signing certificate. Such as:

signingConfigs{
        release{ // Generate the signature configuration for release
            storeFile file('.. /John.jks')
            storePassword '12345678'
            keyAlias 'key0'
            keyPassword '12345678'}}Copy the code

Note: the debug signature file generally located in the $HOME /. Android/debug keystore

For the generated signature configuration, it can be applied to signingConfig in defaultConfig for default signature configuration or to buildTypes for signature configuration for buildTypes. Such as:

buildTypes {
        release {
            signingConfig signingConfigs.release // Configure the release signature
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    
    defaultConfig {
        applicationId "com.example.john.tapeview"
        minSdkVersion 24
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        signingConfig signingConfigs.release  // Configure the default signature
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
Copy the code

3. BuildTypes

BuildTypes signingConfigs and {} {}, is a method of the Android receives is also a domain object NamedDomainObjectContainer, add each are BuildType types.

Each BuildType generates a SourceSet, and the default location is SRC //, so you can specify Java source code and RES resources for it separately. Also, new buildTypes cannot be named main or androidTest (since Android is already built by default), and cannot be named with each other.

(1) applicationIdSuffix

Use to configure applicationID-based suffixes, such as com.john.gradle. sample, specify applicationIdSuffix “.debug” in the debug buildType, Is generated by the debug package called com. John gradle. Sample. The debug.

Note: Library project is not supported

(2) signingConfig

Configure the signature information using defaultConfig as mentioned earlier.

(3) Start zipAlign optimization

Zipalign is a tool for sorting and optimizing APK provided by Android, which can improve the running efficiency of the system and applications, speed up reading and writing APK resources, and reduce memory. Therefore, for published APK, zipAlignEnabled true //true is generally enabled

(4) Clear shrinkResources

Set whether to automatically clear unused resources. The value can be true or false. It should be used in combination with confusion.

(5) Use obfuscation minifyEnabled

Obfuscation is enabled to optimize code, while shrinkResources clean up resources with shrinkResources to shrink APK packages and obfuscate code. The general release is to confuse.

Enable obfuscation: minifyEnabled true //true: enabled; Set up obfuscation rule files using proguardFile and proguardFiles, as described in defaultConfig earlier.

** Note: ** For multi-channel packaging, each productFlavor can be configured with obloquy rule files separately (via their respective proguardFile and proguardFiles).

(6) multiDexEnabled

Whether to enable the function of automatically splitting multiple Dex, which is used to break the setting when the method exceeds 65535

multiDexEnabled true

(7) Debuggable and jniDebuggable

Debuggable: Whether to generate an APK for debugging. The corresponding value is Boolean.

JniDebuggable: Whether to generate a Boolean apK for debugging Jni (C/C++) code;

Android Gradle advanced customization

1. Batch modify the generated APK file name

Android Gradle features three properties which will later become applicationpatterns (which will only work with the Android App Gradle plugin) and libraryVariants (which will only work with the Android Library Gradle plugin). TestVariants (either will work)

Applicationariphone is a collection where each element is a generated product (xxxRelease, xxxDebug, etc.) and it has outputs as an output collection. Traversal, if the name ends in. Apk, is the APK output to be modified.

// Dynamically change the name of the generated APK: project name _ channel name _v version name _ build date.apk
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            if(output.outputFile ! =null && output.outputFile.name.endsWith('.apk')
                    &&'release'==(variant.buildType.name)) {
                def flavorName = variant.flavorName.startsWith("_")? variant.flavorName.substring(1) : variant.flavorNamedef apkFileName = "Example92_${flavorName}_v${variant.versionName}_${buildTime()}.apk"
                outputFileName = apkFileName
            }
        }
    }
    
    ...
    def static buildTime() {
    def date = new Date()
    def formattedDate = date.format('yyyyMMdd')
    return formattedDate
}
Copy the code

2. Configure VersionCode and VersionName in multiple ways

(1) By applying the script plug-in (Apply from)

  1. Create a newversion.gradle(currently stored in the Gradle folder under the project path) and set custom properties

ext{
    appVersionCode = 1
    appVersionName = '1.0.2'
}
Copy the code
  1. Apply the script file in rootProject
apply from : 'gradle/version.gradle'
Copy the code
  1. This setting can be referenced in any subproject:

(2) Directly define the use in the properties file (xxx.properties)

  1. Defined in gradle.properties under the project directory

    3. This setting can be referenced in any subproject:

(3) Obtain the VersionName and versionCode from git tag

/** * use the number of git tags as its version number * @returnNumber of tags */ def staticgetAppVersionCode(){
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git'.'tag'.'--list'
        standardOutput = stdout
    }
    return stdout.toString().split("\n").size()} /** ** Get the version name * @ from git tagreturnGit tag */ def staticgetAppVersionName(){
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git'.'describe'.'--abbrev=0'.'--tags'
        standardOutput = stdout
    }
    return stdout.toString().replaceAll("\n"."")}Copy the code

3. Dynamically configure the AndroidManifest file

During the build process, dynamically modify the contents of the AndroidManifest file

Android Gradle provides a very convenient way to replace the contents of the AndroidManifest file, i.e. ManifestPlaceholder and Manifest placeholders.

Manifestplaceholder is an attribute of ProductFlavor, of type Map, so multiple placeholders can be configured at the same time.

  1. Define placeholders:
. productFlavors{ google{ manifestPlaceholders.put("UMENG_CHANNEL"."google")
    }
    baidu{
        manifestPlaceholders.put("UMENG_CHANNEL"."baidu")}}...Copy the code
  1. Inside AndroidManifes use this placeholder “UMENG_CHANNEL”
. <application> ... <meta-data android:value="${UMENG_CHANNEL}" android:name = "UMENG_CHANNEL"/> ... </application> ...Copy the code
  1. You can also iterate over placeholders
. productFlavors{ google{ } baidu{ } } productFlavors.all{flavor-> manifestPlaceholders.put("UMENG_CHANNEL",flavor.name)
}
...
Copy the code

4. Customize BuildConfig

Android Gradle provides buildConfigField(Srting Type,String Name,String Value) to add constants to BuildConfig. Commonly used in productFlavors or buildTypes:

Note: If value is a String, double quotes must be added, what does this say, buildConfig will put it there exactly as it is

. ProductFlavors {Google {// productFlavors{// "Value" is a String, the double quotes must be added, what does it say, buildConfig will put buildConfigField exactly as it is'String'.'name'.'"google"'
        }
        baidu{
            buildConfigField 'String'.'name'.'"baidu"'}}...Copy the code

5. Dynamically add user-defined resources

Android Gradle provides resValue(String Type,String Name,String Value) to add resources. Can only be used with productFlavors or buildTypes

Note: what is written here will be put in the same place after compilation

6. Configure the Dex option


android {
    ...
    
    dexOptions {
        incremental true // Android studio3.x has been abandoned, whether to enable dx increment mode
        javaMaxHeapSize '4g' // Increase the maximum memory allocation when Java executes dx commands
        jumboMode true // Force the jumboMode mode to be enabled
        pre
    }
    
    ...
}

Copy the code

7. Compile options and ADB action options

android {
    ...
    
    compileOptions {
        encoding = 'utf-8'
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    adbOptions{
      timeOutInMs = 5000 // Set the timeout in ms
      installOptions '-r'.'-s'// Install option, generally not used}... }Copy the code

8. Break method beyond 65535 limit

  1. In defaultConfig or buildTypes or productFlavors, turn on multiDexEnabled: multiDexEnabled True

  2. Increased reliance on: implementation ‘com. Android. Support: multidex: 1.0.3’

  3. Set in custom Application (5.0 + natural support) :

Make the custom Application inherit from MultiDexApplication

Or modify it directly in Java code:

.@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this); }...Copy the code

Multi-channel construction

A Build product (APK), Build Variant = BuildType + ProductFlavor, where ProductFlavor further divides dimensions, Build Variant = BuildType + ProductFlavor’s dimensions

1. Build ProductFlavor properties through multiple channels

. productFlavors{ google{ applicationId"com.john.xxx"}}...Copy the code

(1) applicationId, as described above.

It is the same as manifestplaceholder.

(3) multiDexEnabled, as described above.

(4) proguardFiles, as described above.

(5) signingConfig, as described above.

(6) testApplicationId, as described above.

(7) versionCode and versionName, as described above.

(8) dimension

The dimension of the ProductFlavor can be understood as the grouping of the ProductFlavor

For example, free and paid belong to the Version group, while x86 and ARM belong to the architecture group:

android{
    ...
    
    flavorDimensions "version"."abi"// productFlavors{free{dimension'version'
        }
        paid{
            dimension 'version'
        }
        x86{
            dimension 'abi'
        }
        arm{
            dimension 'abi'}}... }Copy the code

For the above Settings, Build Variant = BuildType + ProductFlavor’s dimensions generates the Assemble task, Variant:

  • ArmFreeDebug
  • ArmFreeRelaese
  • ArmPaidDebug
  • ArmPaidRelease
  • X86FreeDebug
  • X86FreeRelaese
  • X86PaidDebug
  • X86PaidRelease

Refer to the link

The Android Developer’s official website