当前位置:网站首页>Gradle asked seven times. You should know that~
Gradle asked seven times. You should know that~
2022-06-23 21:19:00 【Coating process】
author : Programmer Jiang
Preface
about Android For developers ,Gradle It can also be said to be a familiar stranger , It can be said that it will be used every day Gradle, But for the Gradle Some principles and details of are often not well understood
This paper mainly introduces Gradle Some basic knowledge and principles of , If it helps you , Welcome to thumb up
This article mainly includes the following contents :
GradleWhat is it ?Gradle WrapperWhat is it? ?AGPWhat is it ?gradle.propertiesWhat is it? ?settings.gradleWhat is it? ?build.gradleWhat is it? ?GradleWhat's the life cycle like ?
1. Gradle What is it ?
Gradle It took so long , If you want to describe Gradle, How to answer ? A dependency management framework ? A building framework ?
Gradle It's a Running on the JVM Common build tools , Its core model is a Task Composed of directed acyclic graphs (Directed Acyclic Graphs).

2. Gradle Wrapper What is it? ?
We've been using Gradle, But when you think about it, we're actually useless in the project gradle command , And generally use gradlew command , At the same time, as shown in the figure below , Find the whole project , And gradle These are the two folders , But only found gradle-wrapper.jar.

So here comes the question ,gradlew What is it? ,gradle-wrapper.jar What is it again? ?
wrapper It means : packing .
Well, that's all I can think of , This is a gradle Packaging . In fact, it's like this , because gradle In the fast iteration stage , Often release new versions , If our project directly references , Then changing the version will become very troublesome . And each project may use different gradle edition , In this way, you can manually configure the corresponding... For each item gradle The version will become troublesome ,gradle The introduction of is intended to make it easy for everyone to build projects , If so , Isn't it adding new troubles ?
therefore android Thought of packaging , introduce gradle-wrapper, By reading from the configuration file gradle Version of , Automatic download and configuration for each project gradle, It's that simple . We don't have to worry about how to download gradle, How to configure into the project .
as for gradlew It's the same thing , It has two files ,gradlew Is in linux,mac Under the use of ,gradlew.bat Is in window Under the use of , Provides execution of... On the command line gradle Command functionality
As for why not directly implement Gradle, But to perform Gradlew Orders ?
Because it's like wrapper In itself ,gradle The command line is also fickle , therefore wrapper The command line is also encapsulated , Use the same gradlew command ,wrapper It will automatically execute the corresponding... Of the specific version gradle command .
At the same time, if we configure the global gradle command , In the project, if you also use gradle Easy to confuse , and gradlew Clarity is what is specified in the project gradle edition , Clearer and clearer
3. AGP What is it ?
AGP namely Android Gradle Plugin, namely android Officially developed Gradle plug-in unit , In understanding AGP Before , Let's introduce what plug-ins are first ?
Gradle Itself is a general construction system , It doesn't know what you're compiling Java still C. If it's in Java You need to call javac take .java The file is compiled as .class file , and C You need to call gcc take .c The file is compiled as .o file . It would be too troublesome for each developer to manage these construction processes . So called plug-ins , Is to compile a certain type of template .
and AGP That is, a series of suitable for Android Developed Gradle A collection of plug-ins , such as com.android.application etc. AGP The plug-in provides compileKotlin,compileJava,processResource A series of Task, And set up Task Dependencies between . It also provides many configurable properties . The user only needs to build script Pass through plugins {...} Introducing plug-ins , Configure several properties according to the project situation , You can realize customized Android structure . adopt AGP Plug ins can be implemented quickly Android Construction of the project , This is it. AGP The meaning of plug-ins , During its execution task The list is as follows

4. gradle.properties What is it? ?
except Gradlew And AGP, We also often use gradle.properties, We often gradle.peoperties Define some uniform version numbers in , Such as minSdkVersion,targetSdkVersion etc. , Then in each module Pass through rootProject.minSdkVersion Get to achieve reuse
So here comes the question ,rootProject How to get gradle.properties What about the value defined in ?
The answer is simple ,Gradle It will be read by default at startup gradle.properties, And load the parameters . This is running with us Gradle Pass parameters to it through the command line , The effect is the same
Of course, different ways have different priorities , Specifies the priority of the parameter : Command line arguments > GRADLE_USER_HOME gradle.properties file > Project root gradle.properties file .
GradleTwo directories used :GradleTwo directories will be involved in the execution process , One isGradle User HomeThe other isProject Root Directory.Gradle User HomeUser HomeIt mainly saves the global configuration , Global initialization script and dependent cache and log files . If openbuild cacheWords , The build cache will also exist, which is shared by all projects .
The default is :$USER_HOME/.gradle.Project Root DirectoryProjectThe directory stores content related to the current project construction . For example, for incremental compilation cache .
In general ,gradle.properties In fact, it is a parameter configuration file , It has the same effect as passing parameters on the command line , So in Project You can read
5. settings.gradle What is it? ?
When we execute in a directory gradle On command , The contract will find the following two files from the current directory :
settings.gradle(.kts)build.gradle(.kts)
We are often in settings.gradle Middle configuration module, that settings.gradle What is it ? What's the effect ?
All modules that need to be built need to be in settings.gradle Register in , So its function is to describe “ The modules involved in the current build ”.
settings.gradle The search order is : Start from the previous Directory , If you find settings.gradle(.kts) Then stop , Otherwise, recursively search the parent directory .setting script Undertook the important task of coordinating all modules , therefore api Mainly in the operation of the modules involved in the construction and the plug-ins needed to manage the construction process .
You can register the modules that need to participate in the construction in the following ways , In the project name : Separator representing the item , Similar to... In the path /. If the : The beginning is relative to root project
include(":app", ":libs:someLibrary")
include(":anotherLibrary")
project(":anotherLibrary").projectDir = File(rootDir, "../another-library")
6. build.gradle What is it? ?
When it comes to the most familiar and commonly used build.gradle 了 , There will be one for each module build.gradle To configure the construction information of the current module , Of the root module build.gradle be called root build script, Of other sub modules build script be called module build script.
The process of project construction is roughly as follows , Among them init script finger $GRADLE_USER_HOME In the catalog init.gradle file , Mainly do some initialization configuration
The execution process of single module construction is roughly : init script -> setting script -> build script
The multi module construction process , One more step than a single module : init script -> setting script -> root build script -> build script
generally speaking , root build script Not an actual module , It is used for unified configuration of sub modules , therefore root build script There is usually not much content .
Gradle stay Initialization Phase has not yet been implemented build.gradle(.kts) file , True analysis build script Is in Configuration Stage . however build script The execution of , It doesn't simply execute all the code , Its essence is Describe and configure build rules with code , Then perform the task according to the rules . Build script As a whole Gradle Configure the most complex script in , In fact, only two things have been done : One is to introduce plug-ins , The other is configuration properties
The so-called import plug-ins are as follows ,plugins Closure can also be through version Specify the version of the plug-in , as well as apply To decide whether to apply the plug-in immediately :
plugins {
id("com.android.application")
id("com.dorongold.task-tree") version "1.4"
id("com.dorongold.task-tree") version "1.4" apply false
}
The so-called configuration properties , In fact, it is to configure the imported plug-ins . Original build script Not in China android {...} This dsl attribute , This is a plugin Provided . Once a plug-in is applied , You can use the... Provided by the plug-in dsl Configure it , Thus affecting the construction process of the module . Look at it from another angle , The attribute configuration provided by these plug-ins dsl It's equivalent to a plug-in init The parameters of the function , Finally passed into the plug-in . When the build is executed, the current module will be compiled according to the configuration .
plugins {
id("com.android.application")
}
android {
compileSdkVersion(28)
defaultConfig {
....
}
}
....
7. Gradle What's the life cycle like ?
After understanding the above knowledge , We can start to understand Gradle Life cycle of . In understanding Gradle After the life cycle of , We can Gradle Have an understanding of the overall process of execution , You can also use these life cycles to do something Hook The operation of
Different from the top-down execution of traditional scripts , once Gradle Building involves multiple files , The main process is as follows :

On the whole , Gradle The implementation of is divided into three stages : Initialization -> Configuration -> Execution. Each stage has its own responsibilities .
7.1 Initialization Stage
Initialization The main purpose of this phase is to initialize the build , It is divided into two sub processes , One is to execute Init Script, The other is execution Setting Script.Init script Will read the global script , The main function is to initialize some global properties , For example, get Gradle User Home Catalog , Gradle version etc.
and Setting Script That's what we mentioned above settings.gradle
7.2 Configuration Stage
When the build is complete Initialization After the stage , Will enter the Configuration Stage . This phase starts loading all modules in the project Build Script. So-called “ load ” Is to perform build.gradle(.kts) The statement in , Create the corresponding... According to the script code task, Finally, according to all task Generate the corresponding dependency graph . We said that above "Gradle The core model is a Task Composed of directed acyclic graphs (Directed Acyclic Graphs)" Do you ? This task dependency graph is generated at this stage .
It should be noted that ,Configuration The loading order of each module in the stage is out of order , It has nothing to do with dependency and joining order
7.3 Execution Stage
When the task dependency graph is completed , Gradle You're ready for everything , Then enter Execution Stage . Only at this stage can we really compile and package . about Java Is to call javac Compile source code , And then it's packaged into jar. about Android It's more complicated . These differences come from the plug-ins we use . In general , It's just the beginning of execution task 了
7.4 Life cycle Hook
Gradle Provides a rich life cycle Hook, We can add all kinds of... According to our needs HooK

According to the location of the life cycle in the figure , It is clear that “ The latest registration time in the life cycle ”. such as , settingsEvaluated Is in setting script By evaluated Call back when you're done , So in init script and setting script There is no problem registering in . But if you register in build script in , It doesn't work .
At the same time, about the life cycle Hook, There are also the following points to note
projectsLoadedBeforeProjectNot yet created , So you can only usegradleandsettingsobjectprojectsLoadedThe callback has been based onsetting scriptCreated the of each moduleProjectobject , We can quoteprojectObject to set somehook, That isbuild scriptNot configured yet , So I can't get the configuration information- Whenever a
build.gradle(.kts)It's done , producesafterEvaluateCallback , Represents theprojectByevaluatecomplete . From now on ,projectThe content of the object is complete , namely : At presentbuild.gradle(.kts)All configuration items in the can be accessed . - be-all
ProjectEnd of configuration , CallbacksprojectsEvaluated GradleThe core logic of is based ontaskThe dependence of the graph generates a directed acyclic graph , Then execute the... In the figure in turntask,task graphAfter generation, it will call backgraphPopulated- When all
taskIt's all done , The whole construction is over , This time it's going to callbackbuildFinished
summary
This paper mainly introduces Gradle Some basic knowledge and principles of , Include Gradle Role of each document , And life cycle , Build the overall process , And life cycle Hook Such method
understand Gradle These basic principles , Can help us better understand Android The process of building packaging , It is also convenient for us to use Gradle Do something in the life cycle Hook Work , Improve development efficiency .
边栏推荐
- JS chain call
- Global and Chinese market of roll up piano 2022-2028: Research Report on technology, participants, trends, market size and share
- Initial experience of nodejs express framework
- WinDbg loads mex DLL analysis DMP file
- ES6 promise detailed sewing Red Treasure Book Introduction to ES6 standard
- Use of paging components in fusiondesign
- ntpupdate. tencentyun. Com has been eliminated
- Share a super Mary source code
- 【Redis】有序集合的交集与并集
- C WPF new open source control library: newbeecoder Nbtreeview of UI
猜你喜欢
Application of JDBC in performance test

Steps for formulating the project PMO strategic plan

What are the main dimensions of PMO performance appraisal?

Four aspects of PMO Department value assessment

New SQL syntax quick manual!

How does PMO select and train project managers?

How to gradually improve PMO's own ability and management level

How PMO uses two dimensions for performance appraisal

I am 30 years old, no longer young, and have nothing

How to view the role of PMO in agile organizations?
随机推荐
[tutorial] Tencent lightweight cloud builds an online customer service chat system
What if there are too few jetpack compose theme colors? Design your own color system
Spingboot reads the parameter values in the YML configuration file
Advantages of short video automatic audit? What are the difficulties of manual audit?
How to dispose of the words on the picture? How do I add text to a picture?
[Debian] Debian usage notes
ntpupdate. tencentyun. Com has been eliminated
On line project LAN on-line software use ----phpstudy
Use of pathinfo/pathname in nodejs
Bi-sql index
Global and Chinese market of roll up piano 2022-2028: Research Report on technology, participants, trends, market size and share
Is it safe for flush to open an account online? Is the Commission high
Is it safe to open an online securities account or to go to the business department
How PostgreSQL quickly locate blocking SQL
How to solve the problem of large traffic audio audit? What are the common approval methods?
Retrofit magic, reject duplicate code!
Cobalt Strike Spawn & Tunnel
Does the fortress machine need a server? Understand the architectural relationship between fortress machine and server
打新债到底是用什么软件比较安全?打新债平台有哪些
【Debian】Debian使用笔记