"Reprint" Gradle for Android fourth (build variant)

Source: Internet
Author: User

When you are developing an app, usually you will have several versions. In most cases, you need a development version to test the app and figure out the quality of it, and then you need a production version. These versions often have different settings, such as different URL addresses. More likely, you may need a free version and a paid version. Based on the above situation, you need to deal with different versions: developing the free version, developing the paid version, producing the free version, producing the paid version, and the different configurations for different versions, which greatly increases the management difficulty.

Gradle has some handy ways to manage these issues. We talked a lot earlier about debug and release releases, and now we're talking about another concept, different product versions. Build and production versions can often be merged, and the consolidated version of builds and production versions is called Build variants.

In this chapter we will learn about builds, which can make development more efficient and learn how to use them. Then we'll discuss the differences between build and production versions, and how to merge them. We will explore signature mechanisms, how to sign for different variants, and so on.

In this chapter, we follow the following rules:

    • Build types
    • Product Flavors
    • Build variants
    • Signing configurations
Build version

In Gradle's Android plugin, a build version means defining an app or relying on how the library is built. Each build has a special side, such as whether the Debug,application ID is required, whether unnecessary resources are deleted, and so on. You can define a build version by using the Buildtypes method. For example:

Android {       buildtypes {           release {               false               proguardfiles getdefaultproguardfile                 (  ' Proguard-rules.pro '    }}

This file defines the release version of the module and then defines the location of the Proguard. The release version is not the only build, and by default, there is a debug version. Android Studio treats it as the default build.

Create your own build version

When the default build is not enough, it is also easy to create a build version that you only need to write your own version of in Buildtypes. As shown below:

Android {    buildtypes {        staging {            ". Staging" "            /" http://staging.example.com/api/""} }}

We have defined a staging version that defines a new application ID, which differs from the debug and release versions of ApplicationID. Assuming you use the default configuration, the ApplicationID will be like this:

    • Debug:com.package
    • Release:com.package
    • Staging:com.package.staging

This means that you can install the staging version and release version on your device. The staging version also has its own version number. Buildconfigfield defines a new URL address. You don't have to create everything, so the most likely way is to inherit the existing version.

Android {       Buildtypes {           staging.initwith (buildtypes.debug)           staging {               ". Staging"               "- Staging "               false           }}         }  

The Initwith () method creates a new version and copies all the existing builds, similar to inheritance. We can also make a copy of all the properties of the existing version.

Source Sets

When you create a new build, Gradle also creates a new source set. By default, the folder is not created automatically for you, all you need to create manually.

app└──src├──debug│├──java││└──Com. package│││├──res││└──layout││└──Activity_main. xml│└──Androidmanifest. xml├──main│├──java││└──Com. package│││├──res└──Mainactivity. java└──Constants. java│││││││└──Androidmanifest. xml├──staging│├──java││└──Com.package├──drawable└──layout└──activity_mainres││└──layout││└──activity_main.xml│└── Androidmanifest.xml└──release├──java│└──com.package│└──< Span class= "Hljs-selector-tag" >constants.java└── androidmanifest.xml      

Note: When you add a Java class, you need to know the following procedure, when you add the Customlogic.java to the staging version, you can add the same class to the debug and release versions, but cannot be added to the main version. If you add it, an exception will be thrown.

When using different source sets, the processing of resource files requires a special way. The Drawables and layout files will be overwritten with the duplicate files in main, but the resources under the values file will not. Gradle will merge these resources together with the resources in main.

As an example, when you create a srings.xml in main:

<resources>       <name="app_name" >typesandflavors</<name=" Hello_world ">hello world! </string></resources>           

When you also added Rings.xml in your staing version:

<resources>       <name="app_name" >typesandflavors STAGING</string>  </resources>       

Then the merged strings.xml will be like this:

<resources>       <name="app_name" >typesandflavors STAGING</<name= "Hello_world" >hello world! </string></resources>           

When you create a new build instead of staging, the final strings.xml will be strings.xml in the main directory.

The manifest is also the same as the file under the value file. If you create a manifest file for your build, you do not need to copy the manifest file under the main file, you need to add a tag. The Android plugin will merge them for you.

We will cover more details of the merger in the chapters after the meeting.

Dependency Packages

Each build has its own dependency package, and Gradle automatically creates a different dependency configuration for each build version. If you want to add a logging framework to the debug version, you can do this:

dependencies {

   ' Libs ', include: [' *.jar '])   ' com.android.support:appcompat-v7:22.2.0 '   de.mindpipe.android: android-logging-log4j:1.0.3 '}  

You can combine different builds with different build configurations, just like this, which makes it possible for your different versions of different dependencies to be made.

Product Flavors

Unlike build versions, product flavors is used to create different versions of an app. A typical example is an app that has a paid and free version. Product flavors greatly simplifies building different versions of apps based on the same code.

If you're not sure if you need a new build or product flavors, you should ask yourself if you need internal use and an external use of the APK. If you need a completely new app to publish, and the previous version is completely isolated, then you need product flavors. Otherwise you just need to build the version.

Create Product Flavors

Creating the product flavors is very easy. You can add code to the Productflavors:

Android {    productflavors {        red {             ' com.gradleforandroid.red '             4}   }} 

Product flavors and build versions are configured differently. Because product flavors has its own Productflavor class, like defaultconfig, it means that all of your productflavors share the same attributes.

Source Sets

Just like the build version, product flavors has its own code folder. Creating a special version is as simple as creating a folder. For example, when you have a production version of Blue flavors that has a different app icon, the folder needs to be called bluerelease.

Multiple Flavors build variants

In some cases, you may want to create a merged version of the product flavors. For example, both client A and client B may want a free and paid version, and they are all based on the same code, but there are different colors and so on. Creating four different flavors means there is a duplicate configuration. The simplest way to merge flavors might be to use flavor dimensions, like this:

Android {       "Price"       productflavors {           red {               "price"   }}}

When you add flavor dimensions, you will need to add flavordimension for each flavor, otherwise you will be prompted with an error. Flavordimensions defines different dimensions, and the order of course is also important. When you merge two different flavors, they may have the same configuration and resources. For example, the example above:

    • Bluefreedebug and Bluefreerelease
    • Bluepaiddebug and Bluepaidrelease
    • Redfreedebug and Redfreerelease
    • Redpaiddebug and Redpaidrelease
Build variants

Build variants are a combination of build and production versions. When you create a build version or a production version, the new variant is created as well. For example, when you have the debug and release versions, you create a production version of Red and blue, then there will be four variants:

You can find it in the lower left corner of Android studio, or by view| Tool windows| Build variants open it. This view lists all variants and allows you to switch them. Changing them will affect you by pressing the Run button.

If you don't have product flavors, then the variant simply contains the build, and even if you don't define any builds, Android Studio will create the debug version for you by default.

Tasks

Android Plugin aftertaste each variant to create a different configuration. A new Android project will have debug and release versions, all of which you can use Assembledebug and assemblerelease, and of course when you use the assemble command, both will be executed. When you add a new build, the new task is created. For example:

    • Assembleblue uses the blue flavor configuration and assembles both Bluerelease and Bluedebug.
    • Assemblebluedebug combines the flavor configuration with the build type configuration, and the flavor settings override th e Build type settings.
Source Sets

Build variants can also have their own resource folders, for instance, you can have src/bluefreedebug/java/.

Merging of resource files and manifest

Before packaging the app, the Android plugin merges the code in main and the code that was built. Of course, dependent projects can also provide additional resources and they will also be merged. You may need additional Android permissions for the debug variant. For example, you do not want to declare this permission in main, because this may cause some problems, so you can add an additional Mainfest file in the Debug folder, stating the additional permissions.

The priority for resources and mainfests is this:

If a resource is defined in main and in flavor, then the resource in the flavor has a higher priority. So the resources in the Flavor folder will be packaged into the APK. Resources that depend on project declarations always have the lowest priority.

Create build variants

Gradle makes it easy to deal with building variants.

Android {Buildtypes {Debug {Buildconfigfield"String","Api_url","/" http://test.example.com/api/""} staging.initwith (Android.buildtypes.debug) staging {buildconfigfield  "string",  "Api_url",  "/"/"/" staging.example.com/api/"" Applicationidsuffix  "Staging"}} productflavors {red {applicationid " Com.gradleforandroid.red "Resvalue " color "" Flavor_color ", Span class= "hljs-string" > "#ff0000"} blue {applicationid  " Com.gradleforandroid.blue "Resvalue " color "" Flavor_color ", Span class= "hljs-string" > "#0000ff"}}}           

In this example, we created 4 variants, namely bluedebug,bluestaging,reddebug,redstaging. Each variant has its own API URL and color. For example:

Variant filters

It is also possible to ignore a variant. This way you can speed up your build when using assemble, so that the tasks you list will not perform the variants that you do not need. You can use the filter to add code in the Build.gradle as shown below:

Android.variantfilter {Variant       -and if (Variant.buildType.name.equals (' release ')) {           Variant.getflavors (). each () {flavor-               if (flavor.name.equals (' Blue ')) {Variant.setignore (true) ;            }        }    }}

In this example, we examine the following:

You can see that bluefreerelease and bluepaidrelease are excluded, and if you run Gradlew tasks, you will find that all tasks regarding the above variants no longer exist.

Signature configuration

Before you publish your app, you need to sign your app's private key. If you have a paid version and a free version, you need to have different keys to sign different variants. This is the benefit of configuring signatures. The configuration signature can be defined like this:

   Android {       Signingconfigs {           staging.initwith (signingconfigs.debug)           release {               storefile file (" Release.keystore ")               storepassword" Secretpassword ""               gradleforandroid "               " Secretpassword "           }      }}

In this example, we created 2 different signature configurations. The Debug configuration is as the default, it uses the common KeyStore and password, so there is no need to create a signature configuration for the debug version. The staging configuration uses the Initwith () method, which replicates other signature configurations. This means that the staging and debug keys are the same.

The release configuration uses StoreFile, which defines the key alias and password. Of course this is not a good option and you need to configure it in the Gradle properties file.

Once you have defined the signature configuration, you need to apply them. The build has a property called Signingconfig, which you can do:

Android {       buildtypes {           release {               signingconfig signingconfigs.release           }         }} 

The previous example uses Buildtypes, but you may need to generate different validations for each version, which you can define:

Android {       productflavors {           blue {               signingconfig signingconfigs.release           }       } }

Of course, you define these in flavor, it's best to be rewritten, so the best thing to do is:

Android {       Buildtypes {           release {               productFlavors.red.signingConfig signingconfigs.red               ProductFlavors.blue.signingConfig Signingconfigs.blue           }}}       
Summarize

In this chapter, we discuss build and production versions, and how to combine them. This will be a very useful tool when you need different URLs and different keys, and you have the same code and resource files, but with different types and versions, builds and production versions will make your life better.

We also talked about signature configurations and how to use them.

In the next chapter, you will learn how to build multiple modules, which is important when you want to divide your code into dependencies or dependencies, or if you want to put the Android Wear module in your app.

"Reprint" Gradle for Android fourth (build variant)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.