This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

preface

Gradle dependency management: Gradle dependency management: Gradle dependency management: Gradle dependency management: Gradle dependency management: Gradle dependency management: Gradle dependency management

Release notes

  • This document is recommended for Andoird build configuration
  • Please note that the following Andorid build configurations are for AGP4.2.0 and above

1, the android {}

Android {}, nodes introduced by AGP:

  • CompileSdkVersion: version used for compilation
  • BuildToolsVersion: buildTools version
  • DefaultConfig: Default product flavor
  • ProductFlavors: customize productFlavors
  • BuildTypes: buildTypes
  • CompileOptions: compileOptions
  • SigningConfigs: signature configs

I’m sure all readers will be familiar with this section of the node, so I won’t go into the first two versions and start with defaultConfig.

1.1 defaultConfig{} : Default product flavor

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}
// The application Gradle script introduced by the closure above is the same as the gradle script introduced by the closure below
// apply plugin: 'com.android.application'


// AGP
/ / com. Android. The application provides
// Configure the Android project build
android {
    compileSdkVersion 30 // Use the SDK version when compiling
    // ProductFlavor: ProductFlavor, set for an Android app build
    // defaultConfig specifies the default product flavor
    defaultConfig {
        applicationId "com.hqk.gradledemo03" // Not necessarily the package name
        applicationIdSuffix "aaa" ApplicationId +applicationIdSuffix is the application identifier, which is the package name
        minSdkVersion 21 // The minimum supported version of Android
        targetSdkVersion 30 // Generally, compileSdkVersion is the same for Android SDK versions used for development
        versionCode 1 // The version number of the application
        versionName "1.0" // The version name of the application
        //versionNameSuffix "//versionName suffix
        manifestPlaceholders = [CHANNEL_VALUE: 'hqk'] // The AndroidManifest placeholder type is set by default
        / / testInstrumentationRunner "androidx test. The runner. AndroidJUnitRunner" / / Gradle engine}... A little... Slightly}Copy the code

The AGP (Android Gradle Plugin) script is created by id ‘com.android.application’. The AGP (Android Gradle Plugin) script is created by the Android {} closure.

The AGP here is in the project root directory corresponding to the build. The inside of the gradle classpath “com. Android. View the build: gradle: 2” is introduced. The same goes for the Kotlin script plug-in!

Note: There is an issue here that is easy to overlook.

ApplicationId must represent the package name of APK.

[androidmanifest.xml] [androidmanifest.xml] [androidmanifest.xml] [androidmanifest.xml] [androidmanifest.xml] [androidmanifest.xml] [androidmanifest.xml]

Of course this is a bit of a sensationalist, after all, most people do not use this suffix this thing, the version of namesuffix is so. Let’s move on to the next topic.

1.2 buildTypes {} : Build type

android { ... slightly// Configure the application signature information
    signingConfigs {
        release {
            storeFile file('key_store.jks')
            storePassword "a123123"
            keyAlias "aaa"
            keyPassword "a123123"
        }
        debug {
            storeFile file('key_store.jks')
            storePassword "a123123"
            keyAlias "aaa"
            keyPassword "a123123"}}// Build type: debug, release
    buildTypes {
        release {
// zipAlignEnabled true// Whether to enable zipAlign
            shrinkResources true // Clean up invalid resources
            minifyEnabled true // Whether to enable code obfuscation
            // Specify a configuration file with obfuscated code
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release // Configure the signature file of the corresponding type
        }
// debug{
//
/ /}
// custom{
// initWith release
/ /}}... Slightly}Copy the code

In the buildTypes closure, you can create the corresponding build type. When you create a new module, Android Studio automatically creates a “Debug” build type and a “Release” build type for you. Even if the debug type is not created in buildTypes, Android Studio will use Debuggable True to configure it. This way, you can debug your application on a secure Android device and configure APK signatures using a regular debug keystore.

AndroidStudio will use the default signature configuration, which corresponds to the directory C:\Users\ user host name \.android\debug.keystore

Next came productFlavors, which are common but not common.

1.3 productFlavors{} : customize productFlavors

android { ... Slightly flavorDimensions"channel" // Dimension is a description of the flavor of a product type
    
    // Customization of product flavor, i.e. variation
    productFlavors {
        huawei {
            dimension "channel"
            manifestPlaceholders = [CHANNEL_VALUE: 'huawei']
        }

        xiaomi {
            dimension "channel"
            manifestPlaceholders = [CHANNEL_VALUE: 'xiaomi']
        }

        oppo {
            applicationId "com.oppo.gradledemo03"
            //applicationIdSuffix "aaa" 
            dimension "channel"
            manifestPlaceholders = [CHANNEL_VALUE: 'oppo']}}... Slightly}Copy the code

This comes in handy when we launch different app markets or work with third parties, where different channels require different customization packages.

FlavorDimensions can be used to represent the dimension description of multiple channels. Then you can use productFlavors closure to create channels for different platforms or partners. You can configure different options on the channels according to defaultConfig.

For example, you can have different channel numbers CHANNEL_VALUE, different application package names applicationId+applicationIdSuffix, and even different app versions for different channels.

Doesn’t it smell good? Hahaha, look at the effect.

As is shown in

When packaging is compiled, you will see the multi-channel packaging options we just configured. Select all of them and click Finish to see the final result.

As is shown in

The APK corresponding to different channels has been perfectly packaged here, and the APK application package name corresponding to OPPO has become opPO-related.

Note: “applicationIdSuffix” is not configured in the opPO application package name, but the apK package name of the packaged opPO has a suffix. “applicationIdSuffix” is still in defaultConfig. That is, the following multi-channel unconfigured content will use the properties in defaultConfig by default.

We have just configured the CHANNEL_VALUE for different channels to be different, so how to get it through the logical code?

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        var textViewTxt=findViewById<TextView>(R.id.text_txt)
        var appInfo=packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
        var appName=appInfo.loadLabel(packageManager)
        var appChannel=appInfo.metaData.getString("CHANNEL_VALUE")
        textViewTxt.text=appChannel
    }
}
Copy the code

Add the following code to the androidmanifest.xml file

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

Note: the CHANNEL_VALUE must correspond to build.gradle.

Run the package again to see the effect:

The perfect operation was successful and the effect was realized as expected. But now there is a problem is, different channels version name format is the same, then how to add the version number?

    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def outputFile = output.outputFile
            if(outputFile ! =null && outputFile.name.endsWith('.apk')) {
                // Iterate over all product flavors
                productFlavors.each { flavor ->
                    / / app_v1. 0 _huawei_release. Apk
                    def fileName = "app_v${defaultConfig.versionName}_${flavor.manifestPlaceholders.CHANNEL_VALUE}_${variant.getName()}.apk"
                    outputFileName = fileName
                }
            }
        }
    }

Copy the code

Get the list of all channels and name the different versions and types in the channel number. Now recompile the package all to see the effect:

Here, too, the desired effect becomes the desired one. However, now there is another problem, because there are so many channel packages configured, I don’t want to package all of them every time, I want to directly run the channel number I want and the corresponding DEBUG /release version, then how to operate?

As is shown in

Click the Build option in AndroidStudio and choose the version you would like to run. Then click the run button on AndroidStudio to run the software directly on your test machine. If you want to switch to another version, switch again in this order.

conclusion

That’s about the end of this article. In this and the last one, you have a good understanding of the features we use in Gradle. In the next article, we’ll take Gradle a step further.