Android Gradle use summary (2)

Android Gradle use articles:

Android Gradle use summary (1)

Android Gradle use summary (2)

A custom Android gradle engineering

1, defaultConfig default configuration

defaultConfigIs the default configuration is a ProductFlavour. For multi-channel packages, etc., if not for a custom ProductFlavourconfigured separately, then the default defaultConfigconfiguration

(1)applicationId

Specifies whether the generated app package name, the corresponding value String, such as:applicationId "com.android.xx"

(2)minSdkVersion

App minimum Android OS version supported, the corresponding value inttype (i.e., for the sdk ApiLevel) such as,minSdkVersion 25

(3)targetSdkVersion

The current configuration which sdk version is based on the development, with optional value as minSdkVersion

(4)versionCode

Build number, whose value is the inttype used to configure Android App build number, commonly used version upgrade

(5)versionName

Version name used to configure the app, the corresponding value String, such as "v1.0.0", allowing users to know the current app version. versionCode internal use, external use versionName, control is completed with the version upgrade with app.

(6) testApplicationId

Configuring package name test app, the default is applicationId + ".test" , under normal circumstances, you can use the default.

(7)testInstrumentationRunner

Runner configuration unit for use in testing, using the default android.test.InstrumentationTestRunner.

(8)signingConfig

Configure the default signature information on the app-generated sign. Whose value is the SigningConfigobject. Specific use, view the configuration signature information section .

(9)proguardFile 和 proguardFiles

Both are confusing rules configuration file, the difference is proguardFile to accept a file object, and proguardFiles can accept multiple simultaneous.

(10)multiDexEnabled

Dex whether to start automatically split the plurality of functions exceeds the method for breakthrough 65535, later more specific description

multiDexEnabled true

2, the configuration signature information

Android Gradle provides signingConfigs{}configuration blocks, a plurality of signatures for generating configuration information, whose type is NamedDomainObjectContainer, therefore, we have signingConfigs{}defined is an SigningConfigobject instance.

A SigningConfig, i.e. signature configuration, the configurable element are: storeFile: Signature file location; storeType: Signature Type Certificate (optional); : storePasswordPassword-signed certificate; keyAlias: signed certificate key alias; keyPassword: signing certificate cryptographic keys. Such as:

signingConfigs{
        release{ //生成了release的签名配置
            storeFile file('../John.jks')
            storePassword '12345678'
            keyAlias 'key0'
            keyPassword '12345678'
        }
    }
复制代码

Note: debug signature file is usually located in $ HOME / .android / debug.keystore

For the signature generation configuration can be applied to defaultConfigthe signingConfigperform configuration or default signature applied to buildTypesthe signature type were constructed for the configuration. Such as:

buildTypes {
        release {
            signingConfig signingConfigs.release //配置release类型签名
            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  //配置默认签名
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
复制代码

3, the build type (buildTypes)

buildTypes{}And signingConfigs{}, as is a method of Android, domain object is received NamedDomainObjectContainer, is added to each BuildTypetype.

Each BuildType will generate a SourceSet, the default location is the src //, therefore, may be used alone assign res Java source code and resources. And, the new main or BuildType not be named androidTest (android by default has been generated), and between each other is not the same name.

(1)applicationIdSuffix

Based applicationId for configuring suffix, such as applicationId, specified in the debug buildType for com.John.gradle.sample applicationIdSuffix ".debug", the generated debug package called com.John.gradle.sample.debug

(2)signingConfig

Configuration signature information, use defaultConfig mentioned the same as before.

(3) optimize the start zipAlign

zipalign is finishing android apk provide optimized tools can improve the efficiency of the system and applications, faster read and write apk resources, reduce memory, so apk for release, usually open zipAlignEnabled true //true为开启

(4) resources to clean up shrinkResources

It is configured for automatic cleanup of unused resources, true to open, false to close. To be combined with confusing to use.

(5) use to confuse minifyEnabled

Enable confusion can optimize your code, combined with the shrinkResourcesclean-up resources that can reduce the apk package, you can also obfuscated code. General release is to be confusion.

Open confusion: minifyEnabled true //true为开启; Use proguardFileand proguardFilesdisposed confusion rule file defaultConfig difference between the two as previously described.

** Note: ** For multi-channel packages, each productFlavor confusing rules file can be configured individually (by each proguardFileand proguardFiles).

(6)multiDexEnabled

Dex whether to start automatically split the plurality of functions exceeds the method for breakthrough 65535, later more specific description

multiDexEnabled true

(7)debuggable 和 jniDebuggable

debuggable: for whether to generate a debug apk, corresponding to a boolean value;

jniDebuggable: for whether to generate a debug Jni (C / C ++) code apk, corresponding to a boolean value;

Two, Android gradle Advanced Customization

1, bulk modify apk file name generation

Android Gradle offers three properties, applicationVariants (only for Android applications Gradle plugin), and libraryVariants (only available on Android library gradle plug-in), testVariants (the above two are applicable)

applicationVariants is a collection, each element is a resulting product, i.e. xxxRelease xxxDebug and the like (i.e., generating APK), which has a set of outputs as output. Traversal, if the name ends .apk, then that is to be modified apk output.

//动态改变生成的apk的名字:  项目名_渠道名_v版本名_构建日期.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.flavorName
                def apkFileName = "Example92_${flavorName}_v${variant.versionName}_${buildTime()}.apk"
                outputFileName = apkFileName
            }
        }
    }
    
    ...
    def static buildTime() {
    def date = new Date()
    def formattedDate = date.format('yyyyMMdd')
    return formattedDate
}
复制代码

2, multi-mode configuration VersionCode and VersionName

(1) by applying the script plugins (apply from)

  1. A new version.gradle(currently stored in the project folder path gradle), and set custom properties

ext{
    appVersionCode = 1
    appVersionName = '1.0.2'
}
复制代码
  1. The script file in the application in rootProject
apply from : 'gradle/version.gradle'
复制代码
  1. This setting can be referenced in any of the sub-projects:

(2) is defined directly in a properties file (xxx.properties) in

  1. Gradle.properties defined in the project directory
    3. The setting can be referenced in any of the sub-projects:

(3) obtaining and VersionName versionCode from the tag git

/**
 * 以git tag的数量作为其版本号
 * @return tag的数量
 */
def static getAppVersionCode(){
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git','tag','--list'
        standardOutput = stdout
    }
    return stdout.toString().split("\n").size()
}

/**
 * 从git tag中获取应用的版本名称
 * @return git tag的名称
 */
def static getAppVersionName(){
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git','describe','--abbrev=0','--tags'
        standardOutput = stdout
    }
    return stdout.toString().replaceAll("\n","")
}
复制代码

3, dynamic configuration file AndroidManifest

In the build process, dynamically modify AndroidManifestthe contents of the file

android gradle provides a very convenient way to replace the contents of the file AndroidManifest, i.e. manifestPlaceholder, Manifest placeholder.

manifestPlaceholdersIs a property of ProductFlavor, Map type , can be simultaneously a plurality of placeholders.

  1. Define placeholders:
...

productFlavors{
    google{
        manifestPlaceholders.put("UMENG_CHANNEL","google")
    }
    baidu{
        manifestPlaceholders.put("UMENG_CHANNEL","baidu")
    }
}

...
复制代码
  1. Use placeholder "UMENG_CHANNEL" in the AndroidManifes
...
<application>
    ...
    <meta-data android:value="${UMENG_CHANNEL}" android:name = "UMENG_CHANNEL"/>
    ...
</application>
...
复制代码
  1. Iteration can also modify a placeholder
...
productFlavors{
        google{
        }
        baidu{
        }
    }
productFlavors.all{flavor->
    manifestPlaceholders.put("UMENG_CHANNEL",flavor.name)
}
...
复制代码

4, custom BuildConfig

Android gradle provided buildConfigField(Srting type,String name ,String value)to achieve constant to add BuildConfigin. In general productFlavorsor buildTypesin use :

Note: For a value of type String, double quotation marks must get together, what is written here, buildConfig will put up intact

...
productFlavors{
        google{
            //对于value是String类型的,双引号一定得加上,这里写了什么,buildConfig会原封不动放上去
            buildConfigField 'String','name','"google"'
        }
        baidu{
            buildConfigField 'String','name','"baidu"'
        }
}
...
复制代码

5, dynamic add custom resources

Android gradle provided resValue(String type,String name,String value)to add resources. Only productFlavorsor buildTypesuse

Note: This is what is written, the compiler will put up intact

6, Dex configuration options


android {
    ...
    
    dexOptions {
        incremental true //android studio3.x以上已废弃,是否开启dx增量模式
        javaMaxHeapSize '4g' //提高java执行dx命令时的最大分配内存
        jumboMode true //强制开启jumboMode模式,让方法超过65535也构建成功
        pre
    }
    
    ...
}

复制代码

7, compiler options and adb Options

android {
    ...
    
    compileOptions {
        encoding = 'utf-8'
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    adbOptions{
      timeOutInMs = 5000 //设置超时时间,单位 ms
      installOptions '-r','-s'//安装选项,一般不使用
    }
    
    ...
}

复制代码

8, a breakthrough method exceeds the limit of 65535

  1. In defaultConfigor buildTypesor productFlavorsin the open multiDexEnabled:multiDexEnabled true

  2. Increased reliance:implementation 'com.android.support:multidex:1.0.3'

  3. In custom Applicationsetting (natural support 5.0 and above):

Application inherited the customMultiDexApplication

Or modified directly in the java code:

...
@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}
...
复制代码

Construction of multi-channel

Construction of a product (apk), i.e. Build Variant = BuildType + ProductFlavor, which is further divided ProductFlavor dimensions, i.e. Build Variant = BuildType + ProductFlavor's dimensions

1, multi-channel build ProductFlavor property

...
productFlavors{
        google{
            applicationId "com.john.xxx"
        }
}
...
复制代码

(1) applicationId, as before said.

(2) manifestPlaceholders, as before said.

(3) multiDexEnabled, as before said.

(4) proguardFiles, as before said.

(5) signingConfig, as before said.

(6) testApplicationId, as before said.

(7) versionCode and versionName, as before said.

(8)dimension

As the ProductFlavordimension, understood as ProductFlavora packet

Such as, free and paid version belong to groups, and x86 architecture and arm belonging to the group:

android{
    ...
    
    flavorDimensions "version","abi" //定义分组
    productFlavors{
        free{
            dimension 'version'
        }
        paid{
            dimension 'version'
        }
        x86{
            dimension 'abi'
        }
        arm{
            dimension 'abi'
        }
    }
    ...
}
复制代码

For the above setting, the Build the Variant + = BuildType ProductFlavor apos Dimensions , assemble the generated task, i.e. variant:

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

Reference links

Android Developer's official website

Guess you like

Origin blog.csdn.net/weixin_34283445/article/details/91371411