Getting started with Android Gradle

A preface

Now Android applications are developed using Android Studio, AS the default is to use Gradle AS a build tool. Usually developers can develop an APP without understanding any Gradle scripting configuration. However, if you want to do something more intelligent, such as change the output directory after packaging, speed up packaging, etc., you need to know a little more about Gradle. Gradle scripts are compiled and executed based on the Groovy language, and prior knowledge of the Groovy language is a good idea.

2. Gradle in AS directory

1. You can see Gradle configuration clearly in the Android view

(1)Gradle Version) Configure the Version of Gradle.

The required Gradle version

distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME ZipStorePath = wrapper/dists distributionUrl=https\://

This is the version of the plugin that corresponds to build.gradle under Project

buildscript { repositories { google() jcenter() } dependencies { classpath "Com. Android. Tools. Build: gradle: 4.1.0" gradle version number corresponding to / / / / NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }

(2) Gradle. properties(Project properties) is a configuration file related to the current Project. It mainly contains some information about the key and value pairs needed in the current Project.

org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app"s APK # android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true # BuildToolsver =29.0.0 # Vercode =16 # VerName =1.2 # BuildToolsver =29.0.0 # Vercode =16 # VerName =1.2 # BuildToolsver =29.0.0

(3) Settings. Gradle (Project Settings) is a Project Settings file that tells Gradle the components of the current Project, such as how many subprojects or modules there are

include ':module_red'
include ':module_goods'
include ':module_free'
include ':module_me'
include ':module_login'
include ':common_base'
include ':app' = "KuaiLaiTao"

(4) Build. Gradle (Project) is a gradle configuration file under the root Project. This configuration file is generally used to do some global configuration.

Apply to :"config. Gradle "// Apply to :"config. Gradle "// Apply to :"config. Gradle "// Apply to :"config. Gradle "// Apply to :"config. Gradle "// Apply to :"config. Gradle "// Apply to :"config. Of course, if you use some extra plugins, such as annotation handlers, you can also put them here. Mysql > install Google (); mysql > install Google (); mysql > install Google (); JCenter () is a GitHub code hosting repository that states the configuration of jCenter (). Can be easily quoted dependencies on open source projects jcenter} {the classpath "com. Android. View the build: gradle: 3.5.4" / / here is the android plug-in gradle, Gradle is a powerful tool for the project build classpath 'com. Jakewharton: butterknife - gradle - plugin: 10.2.0' / / butterknife componentization first step / / NOTE: Do not place your application dependencies here; They belong // In the Individual Module Build. Gradle Files}} allProjects {Repositories {// Jcenter like maven repository for Google () () the maven {url "" }}// When running gradle clean, execute the task defined here. // Delete the build directory in the root directory. // This is equivalent to delete. Delete (rootproject.builddir). // Gradle uses the Groovy language to call method without adding (). task clean(type: Delete) { delete rootProject.buildDir }

Build. Gradle (Module) Configure gradle under this Module. This configuration only applies to this Module.

// The first line of code applies the Gradle plugin for an Android application. For an Android application, this step is necessary because the plugin provides all tasks for Android compilation, testing, packaging, and so on. // Android: This is the largest block of code in the build file, and it contains all the special configuration for Android, which is provided by the plugin we declared earlier. BuildToolsVersion "30.0.2" defaultConf {ApplicationID "Com.ruan. mygitignore"// Project package name minSdkVersion 16// Project lowest-compatible version targetSdkVersion 30// Project target versionCode 1// Version number versionName "1.0"/name/version testInstrumentationRunner "androidx. Test. Runner. AndroidJUnitRunner" / / indicates that unit tests are conducted to use AndroidJUnitRunner} / * * * Added Debug and Release signature configuration properties */ signingConfigs {// Automate packaging configuration, Debug {// test environment keyAlias' AndroidDebugKey 'keyPassword 'android' storePassword 'android' storeFile File (' C: / Users/Administrator/android/debug keystore ')} release {/ / online environment keyAlias' rocky 'keyPassword' rockyruan ' StorePassword 'rockyruan storeFile file (' F: / soudaoProject MyGitignore/rocky_ruan JKS')}} buildTypes {/ / production/test environment configuration Release {// Production environment buildConfigField(" Boolean ", "LOG_DEBUG", "false") release {// Production environment buildConfigField(" Boolean ", "LOG_DEBUG", "false") "\"\"")// Config the URL prefix minifyEnabled false// Whether to obfuscate the code proGuardFiles getDefaultProguardFile('proguard-android.txt'), ''// SigningConfig. Release // Sets the signature information pseudoLocalesEnabled false// Whether to generate a pseudo localeno in APK or not. // Whether to perform ZIP alignment optimization on APK packets, reduce the ZIP size, // Add a suffix to the applicationId 'test'// Add a suffix to the applicationId 'test'// Add a suffix to the applicationId 'test'// } debug {// Test environment buildConfigField(" Boolean ", "LOG_DEBUG", "true") "URL_PERFIX", "\"\"")// Config the URL prefix minifyEnabled false// Whether to obfuscate the code proGuardFiles getDefaultProguardFile('proguard-android.txt'), ''// Specifies the obfuscated rule file signingConfig signingConfigs.debug// Sets the signature information debuggable false// Supports breakpoint debugging JNideBuggable False // Enable the NDK code renderscriptDebuggable false// Enable the renderscript is some C written rendering method zipalignEnabled true// Enable the APK package to perform ZIP alignment optimization, reduce ZIP size, // ApplicationId suffix 'test'; // ApplicationId suffix 'test'; // ApplicationId suffix 'test'; // Add a suffix to the applicationID, }} compileOptions {sourceCompatibility JavaScript.version_1_8 targetCompatibility JavaScript.version_1_8}} Dependencies {implementation 'androidx. Appcompat: appcompat: 1.2.0' implementation 'com. Google. Android. Material: material: 1.2.1' implementation 'androidx. Constraintlayout: constraintlayout: 2.0.4' TestImplementation 'junit: junit: 4. +' androidTestImplementation 'androidx. Test. Ext: junit: 1.1.2' androidTestImplementation 'androidx. Test. Espresso: espresso - core: 3.3.0' implementation 'androidx. Recyclerview: recyclerview: 1.1.0' implementation "Implementation" androidx. Swiperefreshlayout: swiperefreshlayout: 1.1.0 'com. Scwang. Smart: refresh layout - kernel: the 2.0.3' // Core must rely on implementation ''// Classics refresh header implementation 'com. Scwang. Smart: refresh - footer - classics: the 2.0.3' / / classic loading implementation 'com. Google. Android: flexbox: 2.0.1' implementation 'com. Squareup. Okhttp3: okhttp: 3.8.0' implementation 'com. Squareup. Okio: okio: 1.12.0' implementation 'com. Google. Code. Gson: gson: 2.6.2' / / rxjava2 implementation 'IO. Reactivex. Rxjava2: rxjava: 2.2.20' implementation 'the IO. Reactivex. Rxjava2: rxandroid: 2.1.1' / / RxLifecycle implementation 'com. Trello. Rxlifecycle3: RxLifecycle: 3.1.0' Implementation 'com. Trello. Rxlifecycle3: rxlifecycle - components: 3.1.0' / / AutoDispose implementation 'com. Uber. Autodispose: autodispose: 0.6.1' implementation 'com. Uber. Autodispose: autodispose - android - archcomponents: 0.6.1' Implementation 'com. Squareup. Picasso was: Picasso was: 2.5.2' implementation 'com. Making. Bumptech. Glide: glide: 4.11.0' AnnotationProcessor 'com. Making. Bumptech. Glide: the compiler: 4.11.0' implementation "Com. Making. Bumptech. Glide: okhttp3 - integration: 4.11.0" implementation "androidx. Work: work - the runtime: 2.5.0"}

DefaultConfig is the default configuration of the application. Note that if the same properties are defined in AndroidMainfest. XML, they will be used mainly here. The most important thing to note here is the applicationID option. In the AndroidManifest.xml we defined, the package name defined there serves two purposes. One is to serve as a unique ID for an application, preventing two identical applications from being installed on the same phone. The other is the package name as our R resource class. In the past we changed this ID to cause all references to the R resource class to be changed. But now if we change the applicationID, we will only change the ID of the current program, not the reference to the resource file in the source code. BuildTypes: Defines compilation types, and we can have different compilation configurations for each type, and different compilation configurations will have different compilation commands. The default types are debug and release. Dependencies: The dependencies that are part of Gradle. It defines additional libraries that the current project needs to depend on. Before we can parse the Gradle build process we need to understand two important objects in Gradle. Each Project is compiled with at least one Project. A build.gradle represents a Project. Each Project contains multiple tasks, which in turn contain many actions. This contains the code that needs to be executed. During compilation, Gradle aggregates all projects and tasks and executes the actions in the task based on the build related files. Because there are many tasks in the build.gradle file, it is necessary to have some logic to execute which task first and which task later. This kind of logic is called dependency logic. Almost all tasks need to depend on other tasks to execute, and tasks that are not dependent will be executed first. So in the end all the tasks form a data structure for a DAG Directed Acyclic Graph. Whenever a Gradle build is executed, three distinct lifecycle phases run: initialization, configuration, and execution.

  • Gradle will create a Project instance for each Project. In a multi-project build, Gradle will figure out which Project dependencies need to be involved in the build.
  • Configuration: Execute the build script for all projects, that is, execute the build.gradle file for each project. It is important to note that the configuration code in the task is also executed at this stage.
  • Execution: Gradle executes tasks in the order of dependencies.

Execution order:

> Configure project: > Configure project :app build. Gradle Configure app build. Gradle Configure :app build. Gradle Configure :app build

All modules have been configured

AssembleDebug will print the Debug package

AssemblereEase releases the package

Assemble will publish both the debug package and the release package

1. The android Task:

The MD5, SHA1, and SHA256 values of the signature file under debug and Release are available Task:

Execution of the build dependency compile Assemble setup

4.clean up


Install a Debug/Release version on the device


Click on the APK generated by packaging AssemblereEase in the app under the build-fair-relase package

The display is an unsigned official package

But if the build.gradle configuration under the app

BuildTypes {/* Official version */ release {minifyEnabled false// Code obfuscation /* Code obfuscation rule */ ProGuardFiles getDefaultProguardFile('proguard-android-optimize.txt'), '' //debuggable false // This build type should generate the adjustable APK signingConfig signingConfigs.release // Set the default call to the signingConfigs.release} we just configured above

SigningConfig SigningConfigs. release calls the signature file configured above

You can also use Gradlew Assemblerease from the command line under Terminal


Build Task relies on the Check task, but does not depend on ConnectedCheck or DeviceCheck. Lint generates several files when the Check task is executed, which can be used in the

End: Knowledge needs constant learning