Gradle Introduction
?? Gradle is an automated build tool that uses groovy's domain specific Language (domain-specific language) to describe and control building logic. It has the features of simple syntax, strong readability and flexible configuration. Android Studio, based on the IntelliJ idea Community version, was born to support the Gradle build program. Groovy is a JVM-based Agile development language that combines many of the powerful features of Phthon, Ruby, and Smalltalk. At the same time, groovy code works well with Java code and can be used to extend existing code.
Gradle has the following features:
- Gradle support for multi-project construction and local construction
- Gradle supports remote or local dependency management: support from remote maven repositories (Project builder, software project management integrated tools), nexus (a special remote repository within LAN), Ivy Warehouse (Tools to manage project dependencies), and local warehouse acquisition dependencies
- Gradle is compatible with Ant, maven
- Gradle can be easily migrated: Gradle works for any structure and can be built in parallel with the same development platform for both original and Gradle projects
- Gradle Use flexibility: Gradle's overall design is a language-oriented, rather than a rigid framework
- Gradle free Open Source
- Gradle is well integrated with the IDE
- Gradle can be easier to integrate into an automated build system
Gradle configuration for project building under Android Studio
?? Under Android Studio, create an Android project and switch to Project view to see the structure of the item.
?? The red box mark is the Gradle related configuration file in the project, below we begin to analyze each configuration file from Build.gradle under the app module.
Build.gradle file description under App module
?? The Gradle configuration file under this module is the main Gradle profile for the entire project, primarily configuring application properties, configuring application signatures, configuring application features (channels), configuring application build types, and configuring application dependencies, which are the default generated file content:
1. Application plugin Apply plugin There are three types of values, respectively:
apply plugin: ‘com.android.application’//这表示此module是一个可运行的应用程序,可以直接run的apply plugin: ‘com.android.library’//这表示此module是一个安卓依赖库的工程,不可直接runapply plugin: ‘java’//这表示此module是一个java项目,在此module中只能使用java的api
2. About Android closures,
?? The default is Compilesdkversion, Buildtoolsversion, defaultconfig closures, and buildtypes closures.
?? Compilesdkversion and buildtoolsversion are two parameters about the version description
25//指定编译版本,开发采用的sdk版本buildToolsVersion “25.0.2”//编译时采用的构建工具的版本
?? defaultconfig Closure Parameter Description
applicationId “com.jointem.variantpackaging17251//应用版本号,更新需要,新包的值要大于老包的方可更新versionName ‘1.0’//应用版本名,通常用于显示testInstrumentationRunner”andrid.support.test.runner.AndroidJUnitRunner”//Android单元测试test runner
?? buildtypes Closure Parameter Description
?? About the build type BuildType, the default is release and debug two, the default only shows the release method, usually the official release of the package.
false//混淆开关proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’// 指定混淆文件及混淆文件规则配置文件的位置
3. About module Dependency dependencies
Compile Filetree (include: [' *. Jar'], dir: ' Libs ')//Compile the file tree (compile dependent libs directory for all Jars) androidtestcompile ('com. Android. Support. Test. Espresso: Espresso-core:2.2. 2', {Exclude group: 'com. Android. Support', module: ' Support-annotations '}) Compile 'com. Android. Support: appcompat-v7:24.2. 1'//is to download a dependency package from repository (default is Jcenter ()) to compile and package compile 'com. Android. Support. Constraint: constraint-layout:1.0. 0-beta5 ' Testcompile ' junit:junit:4.12'//is only valid for compilation and compilation of unit test code and final package test apk, and does not work for normal Debug or release APK package Compile project (': Andr-library ')// is to compile and package the other module
?? In fact, the script under the app corresponds to the settings in the Project Structure dialog box, from left to right, which are properties, signatures, channel features, build types, and dependencies, shortcut keys Ctrl+shift+alt+s (windows/linux), as follows.
Second, the Build.gradle configuration under the Library module
?? In addition to the app module, each module also has a gradle configuration file, the syntax is the same, the difference is that the beginning of the declaration is the application plugin: ' Com.android.library ', indicating that the module is in the form of dependent modules exist.
Third, global configuration file
?? All global profiles are placed at the root of the project, including ignored files, local configuration files, Gradlew batch files, and project Gradle-related configuration files.
1.gradle configuration file gradle-wrapper.properties, the default content is as follows:
#Thu Mar 09 16:27:37 CST 2017distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/distszipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdistributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
?? This configuration file mainly declares the directory of Gradle and the download path and the Gradle version used by the current project, these default paths we generally do not change, the Gradle version indicated in this file is not one of the reasons why many of the guide package is unsuccessful.
2. About project under Build.gradle configuration file
?? The gradle basic configuration file for the entire project, which is used to configure the project's build tasks as follows:
Top-level buildfilewhere you canAddConfiguration Options Common toAll Sub-projects/modules.//project build file, you can add common configuration options in each sub-project/module. Buildscript {//android plugin download from this warehouseRepositories {Jcenter ()//dependent on the name of the warehouse source, compatible with MAVEN's Remote central warehouse}//Project dependentdependencies {//android gradle plug-inClasspath' com.android.tools.build:gradle:2.3.0 ' //Note:do not place your application dependencies here; they belong //In the individual module Build.gradle files}}allprojects {//Configure the default warehouse source in project here, including dependencies for each module, without having to configure each module separatelyrepositories {Jcenter ()}}//Perform clean tasks before packing//task type is deleteThe //clean task is to delete the files in the build directory under the project root directoryTask Clean (type:delete) {DeleteRootproject.builddir}
3. About the Gradle configuration file gradle.properties
?? Gradle.properties is a configuration file for Gradle, Build.gradle is built by reading the parameters of this file configuration, and some global parameters (global proxies) can be configured in this configuration file. The default file contents are as follows:
# project-wide Gradle settings.# IDE (e.g. Android Studio) Users:# Gradle settings configured through the IDE *will override*# Any settings specified in this file.# For more details about how to Configure your build environment visit# http://www.gradle.org/docs/current/userguide/build_environment.html# Configure JVM parameters for Daemons# Specifies the JVM arguments used for the daemon process.# The setting is particularly useful for tweaking memory settings.org.gradle.jvmargs=-xmx1536m#配置完成后, Gradle will run in parallel mode (parallel compilation)# When configured, Gradle'll run in incubating parallel mode.# This option is should only is used with decoupled projects. More details, visit#http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects# org.gradle.parallel=true
4. About global configuration file Setting.gradle
?? Default file contents include ': App '. Is the global configuration file for the project, which mainly declares some modules that need to be added to the build. In Android studio, it is usually the default to automatically add dependent module to this file.
How to rely on Android Studio One, Project Structure
?? Press the shortcut key Ctrl+shift+alt+s (Windows/linux) to open the project structure Pop-up window.
?? There is a scope under dependencies, where you can choose how to rely, with options such as compile, provided, APK, Test compile, Debug compile, and release compile, These options are briefly described below.
- Compile: All build Type and favlors are compiled and packaged into the final apk file, and a dependency package is downloaded from repository (the default is Jcenter ()) to compile and package.
- Provided:provided is for all build type and favlors is only used at compile time, like external-libs in Eclipse, only participates in compiling, not packaging to the final apk, is provided to those who only compile the non-packaged scenes of the command. Is that I have a dependency on a jar file when I compile it, but when I finally package the apk file, I don't want to put the jar file in it, so I can use this command.
- APK: will only be packaged into the APK file, not the compilation, so you can not call the code directly in the Jar class or method, otherwise at compile time will be error.
- Test compile: Only valid for compilation and compilation of unit test code and final package test apk, but not for normal debug or release APK package.
- Debug compile: Only for debug mode compilation and final Debug APK package.
- Release compile: Only for release mode compilation and final release APK package.
Ii. two sub-parameters about compile:
- Compile files: Find Picasso-2.4.0.jar This file from the local Libs directory to compile and package. A similar command would be to
compile fileTree(dir: ‘libs‘, include: ‘*.jar‘)
compile and package all the jar files in the Libs directory.
- Compile project: A second module (equivalent to the library in Eclipse) is compiled and packaged.
Why should I pack a variant package?
?? In the development process often encountered multiple environment switching problems, for example, is connected to the test environment for debugging, at this time and want to see the production environment data display, the usual way is to remove the test environment and then run a production environment package. As we all know, build a big project until it's installed on the phone, the whole process is time-consuming. If you can install multiple apk on the same app at the same time on the same phone, then when you want to look at data from another environment, you don't need to uninstall and install it (similarly, the same app, which requires different versions of the installation package [Free version/paid version], can also be handled, Instead of having to create different branches for different versions).
Ii. conditions for packaging variant packages
?? After creating a project, we can see a ApplicationID property in the Defaultconfig node under the Android node in Build.gradle under the app module, the default ApplicationID and The package property in Androidmanifest.xml is the same. ApplicationID and PackageName, what do they each represent? Why would it be the same? In fact, the package represents the packages name in the Java code, and the resources in the application are identified by package (for example, r file, packet name). R); ApplicationID represents the unique identity in the app and is used with the application signature to differentiate it from other applications.
?? On the phone, the system also uses applicationid and signatures to identify an app. So, as long as we are packaging the APK, so that the application between the ApplicationID and the signature is different, you can implement the same application of the various variants are installed on the same phone. At the same time, in order to better differentiate to a variety of applications, we can also use the placeholder, using Gradle to configure different resource files, different application names and icons, different Java files and other differentiated properties, different variant packages.
Iii. to play the variant package Step 1. Configure signatures, channels (ApplicationID)
?? Select the App module, select the Signing tab, first configure the two variant versions of the signature file, the file name can be arbitrarily taken (see name).
?? Signature attribute Field Description:
- keyalias//Specifies the alias of the signature file
- keypassword//alias pairing password for the specified signature file
- storefile//Signature File path
- storepassword//the password for the signature file
?? Switch to the Flavors tab, configure the related properties of the variation package, because the next time you create a resource folder, you need to correspond to the file name here, so the name here is as simple as possible. Here I create two named Dev and Rea flavor, all of the flavor will replicate the properties in Defaultconfig, so I can see that I did not fill in some of these properties. The key point here is to set different ApplicationID for different variants and select the corresponding signing Config.
2. New Sourceset of different variants
?? After modifying the variant's profile, we also need to re-create a new folder under the SRC folder for our flavor name, and create the same directory structure under those folders as in Main.
?? We normally write the project is written in the Sourceset under Main, but if our project variants have different resource files, Java files, we need to use different sourceset to distinguish the open.
?? It is important to note that the resource file under flavor is merged with Main, and if there are duplicates, the priority in flavor is higher than in main. We can store the resources of different variants in main and store only the different contents in the Flavor sourceset.
?? If there are different versions of the Java file with different content, it is important to note that the Java file needs to be placed in each flavor Sourceset folder, main can not have this Java file, if there is also this file in Main, the compilation will prompt the file duplication. For example, there are two variants, have different Targetactivity.java, then main can not have this file, need to put this Java file to each flavor Sourceset, and this Java file in the Sourceset to follow the package structure in main to save.
3. About configuring different launcher icons and app names
?? With the previous operation, the ApplicationID, Signing config and Java files of the variant package can be effectively distinguished, so how to apply the logo and name, there are two ways.
1) Configure different resources: We can use a method similar to working with Java files, configure the App_name property in the String.xml in different sourceset, and place the corresponding Ic_app.png icon resource in the Mipmap folder. However, when we need to change the launch map and the application name and the variant package is more than the case, this method will be more troublesome, because we have to go to each sourceset resource file corresponding changes, if the use of placeholders, it will become simpler.
2) How to use placeholders: use placeholders in the Androidmanifest file and then configure them directly in flavor, the properties used in flavor are Manifestplaceholderss (manifestplaceholders =[ Name1:value1]), and both the icon resource and the app name can be placed directly in main.
Results such as:
Iv. Select Variant at Debug 1. Select the app you want to debug
?? Through the previous operation, has successfully configured several variants, then the question comes, so many variants, when we debug, how do we choose to debug the variant? There are two ways of switching.
- Select the Build->select build variant, and the build variant will appear in the lower left corner, and click to select the variant you want to compile.
- Another way is to directly click on the lower left corner of the build variant to select the card, followed by the same action.
2. Places to be aware of
- Here you can see there are 4 variants, which is why? We only have two variants configured? In this need to mention the build type configuration, there are two types under this tab, the default is debug and release, the number of variant packages is exactly (build type number) * (number of flavor).
- When you finish selecting the variant you want to compile, you will find that there are no resource errors found under the selected variant, which is normal and will become the normal project folder style when selected, and this error will not affect our bulk packaging.
V. Common GRADLEW commands
?? First run the command line, there is no gradle to download Oh, download the time depends on the network conditions.
1. Eight Common commands:
- ./gradlew-v//View Gradle version
- ./gradlew Assembledebug//compiling and typing the debug version of the package
- ./gradlew assemblerelease//compiling and typing the release version of the package
- ./gradlew Build//Perform a check and compile the package, typing all release and debug packages
- ./gradlew clean//Delete build directory, will delete the build directory below the app
- ./gradlew Installdebug//compile package and install debug versions of packages
- ./gradlew Uninstalldebug//Uninstalling the Debug version of the package
- ./gradlew-info//Use-info to view task details
2. Command line terminal terminal Execute the Package command
?? We directly use the./gradlew build to make all the variant packages, type them under Terminal terminal./gradlew build command, need to wait about 20 seconds, when you see the terminal print out a build successful, indicating that the package task execution is complete, Open the specified APK build directory (default app/build/outputs/apk) to see the apk that has been played.
?? Install all two release packages to the same phone, and you can see that they can be present and run normally.
3. Holes to be noticed in packaging
?? If the library module is present in the project and the application under manifest in the Library module also has the same attribute tag as the application under the app module, Then you will be prompted for manifest.xml merge errors, as follows.
- Reason: This is because the Gradle plugin for as is enabled by default manifest merger Tool, and if the same properties as the master project are defined in the library project (for example, Android:icon and Android:theme generated by default), merge fails at this time , and report the above error.
- Workaround: Add tools:replace= "Android:icon, Android:theme" (multiple attributes, separated by, manifest.xml) under the application tag of the And remember to add xmlns:tools= "Http://schemas.android.com/tools" to the manifest root tag, otherwise you will not find namespace OH).
Note: This blog is purely personal notes, if the wrong place, but also hope to help correct, thank you!
Gradle Configuration and Packaging application variants for project construction under Android Studio