Gradle

Introduction of Gradle

Gradle is an open source tool for automated project building based on the concepts of Apache Ant and Apache Maven. It supports Maven, Ivy repositories, and transitive dependency management without requiring remote repositories or pom. XML and Ivy. XML configuration files. Gradle uses a Groovy-based domain-specific language (DSL) to declare project Settings, and now adds a Kotlin-based DSL based on the Kotlin language, ditching the tedious XML-based configuration.

Gradle currently supports Java, Kotlin, Groovy, and Scala, with more languages to come. In normal Android development, Android projects are built using Gradle, as shown below.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.xzh.gradleplugin"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx. Appcompat: appcompat: 1.0.2'
    implementation 'androidx. Constraintlayout: constraintlayout: 1.1.3'
    testImplementation 'junit: junit: 4.12'
    androidTestImplementation 'androidx. Test: runner: 1.1.1'
    androidTestImplementation 'androidx. Test. Espresso: espresso - core: 3.1.1'
}

Copy the code

Android Studio also integrates Gradle’s build tools, such as the following common scenarios for building our projects.

Common commands

The command instructions
-v, –version View the current Gradle version
– h: Viewing Help Information
-s, –stacktrace / -S, –full-stacktrace If an exception occurs, output the exception stack information
-i, –info / -d, –debug Controlling log Levels
–stop Stop running Daemons
-D, –system-prop / -P, –project-prop Passing in a specific parameter
-m, –dry-run / -x, –exclude-task Run the build without actually performing the task
–offline / –refresh-dependencies Build in offline mode, forcing the refresh of dependent builds
b, –build-file / -c, –settings-file Specify build script, specify Settings script
Ctrl + c Terminate current run
./gradlew aFR > log.txt 2>&1 Output everything to log.txt

Gradle Wrapper

Gradle Wrapper simplifies the installation and deployment of Gradle itself. Different versions of Gradle projects may require different versions of Gradle. Manual deployment can be cumbersome and can cause conflicts, so Gradle Wrapper is needed to handle these things. Gradle Wrapper is part of the Gradle project.

In Android application development, we often see the following code:

distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME ZipStorePath = wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zipCopy the code

Its purpose is to simplify Gradle configuration. Understand Gradle, Gradle Wrapper and Android Plugin for Gradle

Gradle Task

Gradle Task commands are often used in Android packaging and APK building. Some of the common ones are as follows.

The command instructions
tasks [–all] Lists all runnable tasks
help –task <task> View the help information about a task
androidDependencies View the Android dependency tree for the current project
dependencies –configuration <config> View the dependency tree of configuration
clean Clean up the build output
assemble, assemble{BuildVariant} Build apK, build APK specified Variant
install Build apK and install it
uploadArchives Build the AAR and upload it to the specified dependency management server

AssembleRelease relies on many tasks during an Android project build. Here are some of the key tasks.

The command instructions
compileReleaseJavaWithJavac Compiling Java files
mergeReleaseAssets Collect all assets
mergeReleaseResources Collect all resources
processReleaseManifest Generate the final AndroidManif.xml file
transformClassesAndResourcesWithPro guardForRelease confusion
transformClassesWithDexForRelease Generate dex
packageRelease Package to generate APK

Build life cycle

The Gradle Build cycle can be divided into Initialization, Configuration, and Execution according to the Build Phases and Settings file.

  • Gradle can build one or more projects. During the initialization phase, Gradle determines which projects are involved in the build and creates a Project instance for those projects.

  • In this phase, the Project object is configured. Build scripts will execute for all projects built. That is, the build.gradle file for each project is executed.

  • Gradle determines the subset of tasks to be created and configured during Execution. The subset is determined by the task name parameter passed to the gradle command and the current directory. Gradle then executes each selected task.

Android APK building process

2. Use the AIDL tool to generate the corresponding Java file. 3. Use the dex tool to compile the class files and third-party JAR packages into dex files. 5. Use aAPT to compile the resource files under res into binary files. Then package it, the dex file in the previous step and the files in assets into apK files through apKBuilder. 6. Sign the APK through Jarsigner

The Android APK build process can be depicted in the following diagram, as shown below.

Gradle plug-in development

Create the Gradle plug-in

To create a Gradle plugin project, run the following command:

brew install gradle
Copy the code

After the installation is complete, create a new empty project and use Gradle Init in the project directory to create the project.

public class GradlePlugin implements Plugin<Project> {
    public void apply(Project project) {
        // Register a task
        project.tasks.register("greeting") {
            doLast {
                println("Hello from plugin 'xzh.plugin.greeting'")}}}}Copy the code

This command registers the GradlePlugin plugin with Gradle, with the following code:

gradlePlugin {
    // Define the plugin
    plugins {
        greeting {
            id = 'xzh.plugin.greeting'
            implementationClass = 'xzh.plugin.GradlePlugin'}}}Copy the code

Then, on the command line, execute the gradle copy command, which corresponds to the following code:

task copy(type: Copy, group:"Custom", description:"task description") {
    from "src"
    into "dest"
}
Copy the code

The above code copies the SRC file to the dest directory.

Develop plug-ins and publish them locally

Sometimes we need to develop Gradle plug-ins and publish them to a Maven or Jcenter repository for others to use. Here, for convenience, we send it locally and then pull the local plug-in as well.

Suppose we have developed a plug-in project and now want to publish it to a local repository (a remote Maven repository), as shown below.


apply plugin: 'maven'UploadArchives {repositories. MavenDeployer {/ / configure local repository path, the project under the root directory of the repository directory repository (url: uri ('/Users/xiangzhihong/Maven/repository'))
        pom.groupId = "com.xzh.viewlib"// Unique identifier (usually the module package name, but optionally) pom.artifactid ="OXViewLib"// Project name (usually the library module name, but optionally) POM.version ="1.0.0"// Version number}}Copy the code

After the configuration is complete, click “Sync Now” to rebuild the project. In the Gradle Projects window, a new upload directory will appear, which contains a task named uploadArchives. UploadArchives is the task that publishes the library to the repository.

Maven {allProjects {repositories {Google () jCenter () // Maven {url'/Users/xiangzhihong/Maven/repository'}}}Copy the code

Then add the dependency to build.script under app.

 implementation 'com. XZH. Viewlib: OXViewLib: 1.0.0'
Copy the code

Then click Sync Now to rebuild the project and you can use the code of the Gradle plugin in your Android project. Of course, if you want to publish to a remote Maven repository, you need to configure the Maven repository, but the process is similar.