What is Gradle in Android Studio?

 

Short Answer

Gradle is a build system.

Long Answer

Before Android Studio you were using Eclipse for your development purposes, and, chances are, you didn't know how to build your Android APK without Eclipse.

You can do this on the command line, but you have to learn what each tool (dx, aapt) does in the SDK. Eclipse saved us all from these low level but important, fundamental details by giving us their own build system.

Now, have you ever wondered why the res folder is in the same directory as your src folder?

This is where the build system enters the picture. The build system automatically takes all the source files (.java or .xml), then applies the appropriate tool (e.g. takes java class files and converts them to dex files), and groups all of them into one compressed file, our beloved APK.

This build system uses some conventions: an example of one is to specify the directory containing the source files (in Eclipse it is \src folder) or resources files (in Eclipse it is \res folder).

Now, in order to automate all these tasks, there has to be a script; you can write your own build system using shell scripting in linux or batch files syntax in windows. Got it?

Gradle is another build system that takes the best features from other build systems and combines them into one. It is improved based off of their shortcomings. It is a JVM based build system, what that means is that you can write your own script in Java, which Android Studio makes use of.

One cool thing about gradle is that it is a plugin based system. This means if you have your own programming language and you want to automate the task of building some package (output like a JAR for Java) from sources then you can write a complete plugin in Java or Groovy(or Kotlin, see here), and distribute it to rest of world.

Why did Google use it?

Google saw one of the most advanced build systems on the market and realized that you could write scripts of your own with little to no learning curve, and without learning Groovy or any other new language. So they wrote the Android plugin for Gradle.

You must have seen build.gradle file(s) in your project. That is where you can write scripts to automate your tasks. The code you saw in these files is Groovy code. If you write System.out.println("Hello Gradle!"); then it will print on your console.

What can you do in a build script?

A simple example is that you have to copy some files from one directory to another before the actual build process happens. A Gradle build script can do this.

 

 

Gradle 完整指南(Android)

 

之前的编译工具

在 Gradle 出现以前Android 也有对应的编译工具叫 Ant,在Gradle 出现之后,也有新的编译工具出现,就是FaceBook 的Buck工具。这些编译工具在出现的时候几乎都比 Gradle 要快,Gradle 之所以慢是跟它的编译周期有很大关系。

 

编译周期

每个项目的编译至少有一个 Project,

一个 build.gradle就代表一个project,

  |---- 每个project里面包含了多个task,

很多actionaction是一个代码块,里面包含了需要被执行的代码。

 

在编译过程中, Gradle 会根据 build 相关文件,聚合所有的projecttask,执行task 中的 action。

因为 build.gradle文件中的task非常多,先执行哪个后执行那个需要一种逻辑来保证。这种逻辑就是依赖逻辑

几乎所有的Task 都需要依赖其他 task 来执行,没有被依赖的task 会首先被执行。

所所有的 Task 会构成一个 有向无环图(DAG Directed Acyclic Graph)的数据结构。

 

编译过程分为三个阶段:

  • 初始化阶段:创建 Project 对象,如果有多个build.gradle,也会创建多个project.
  • 配置阶段    :在这个阶段,会执行所有的编译脚本,同时还会创建project的所有的task,为后一个阶段做准备。
  • 执行阶段    :在这个阶段,gradle 会根据传入的参数决定如何执行这些task,正action的执行代码就在这里。


一般创建一个android项目后会出现两个gradle,以及一个settings:

  • build.gradle(Project):用来配置整个工程的 ----> (1)
  • build.gradle(app):一个是用来配置app的 ----> (2)
  • settings.gradle:定义了哪些module 应该被加入到编译过程,对于单个module 的项目可以不用需要这个文件

 

 

(1)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {      // 定义了 Android 编译工具的类路径
    repositories {
        jcenter()    // 是一个著名的 Maven 仓库
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {      // 定义的属性会被应用到所有 module 中,但是为了保证每个项目的独立性,我们一般不会在这里面操作太多共有的东西
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

JCenter是Goovy Grape内的默认仓库;

Gradle内建支持jcenter()仓库,项目库打包成aar文件类似jar,只是多了res,lib文件的包,

上传到jcenter后,可以很方面的在本地调用库文件。

 

 

(2)

plugin
AndroidMainfest.xml

 

Gradle Wrapper

产生原因:新的版本难免会对以往的项目有一些向后兼容性的问题。

包含一些脚本文件和针对不同系统下面的运行文件。

Wrapper 有版本区分,但是并不需要你手动去下载,当你运行脚本的时候,如果本地没有会自动下载对应版本文件。

distributionBase = GRADLE_USER_HOME
distributionPath = wrapper/dists
zipStoreBase     = GRADLE_USER_HOME
zipStorePath     = wrapper/dists
distributionUrl  = https\://services.gradle.org/distributions/gradle-4.1-all.zip

 

命令执行

程序不自动创建wrapper脚本的话,我们需要手动创建。

gradle wrapper --gradle-version 2.4

Gradle 会根据build 文件的配置生成不同的task,我们可以直接单独执行每一个task,列出所有task:

./gradlew tasks

android system_server和AMS是通过socket通信的吗_Android

android system_server和AMS是通过socket通信的吗_Google_02

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for each variant.
sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project '01a_Google-Maps-Google-Places'.
components - Displays the components produced by root project '01a_Google-Maps-Google-Places'. [incubating]
dependencies - Displays all dependencies declared in root project '01a_Google-Maps-Google-Places'.
dependencyInsight - Displays the insight into a specific dependency in root project '01a_Google-Maps-Google-Places'.
dependentComponents - Displays the dependent components of components in root project '01a_Google-Maps-Google-Places'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project '01a_Google-Maps-Google-Places'. [incubating]
projects - Displays the sub-projects of root project '01a_Google-Maps-Google-Places'.
properties - Displays the properties of root project '01a_Google-Maps-Google-Places'.
tasks - Displays the tasks runnable from root project '01a_Google-Maps-Google-Places' (some of the displayed tasks may belong to subprojects).

Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.

Result

 

列出每个task 对应依赖的其他task,可以使用:

./gradlew tasks -all

 

Android tasks

其实每当我们在Android Studio点击 build, rebuild, clean菜单的时候,执行的就是一些gradle task。

有四个基本的 task, Android 继承他们分别进行了自己的实现:

  • assemble:对所有的 buildType 生成 apk 包。
  • clean:移除所有的编译输出文件,比如apk
  • check:执行lint检测编译。
  • build:同时执行assemblecheck命令

可选择性编译:

默认的 assmeble 会依赖 assembleDebug 和assembleRelease,

如果直接执行assmeble,最后会编译debug,和release 的所有版本出来。

如果我们只需要编译debug 版本,我们可以运行assembleDebug

 

Jeff: 暂时到此为止,有点难和繁杂。