7 practical Gradle tips you should know

7 practical Gradle tips you should know

Preface

Gradle
in
android
The application is very extensive in development, but I believe that many students don t know much about it
gradle

This article mainly introduces the use of
gradle
Some practical tips to help readers improve their understanding of this familiar stranger
mainly include the following

  • 1.
    Gradle
    Dependency tree query
  • 2. Use loop optimization
    Gradle
    Dependency management
  • 3. Support code hints
    Gradle
    Dependency management
  • 4.
    Gradle
    Modular
  • 5.
    Library
    Module
    Gradle
    Code reuse
  • 6. Resource file subcontracting
  • 7.
    AAR
    Quick switch between dependency and source code dependency

1.
Gradle
Dependency tree query

Sometimes when we analyze dependency conflicts, we need to view the dependency tree. The command we commonly use to view the dependency tree is

gradlew App: the Dependencies copy the code

However, there is too much information to view the dependency tree in this command line method, and it is a bit difficult to read,
so the official release

Scan
Tools to help us view the dependency tree more conveniently
Run under the project root directory location
gradle build --scan
OK, and then it will generate
HTML
Analysis file of format analysis file

The analysis file will be uploaded directly to

Scan
Official website, the command line will give you the remote address at the end
. The first run will let you
Scan
Register on the official website and you will be able to read it after confirming the email
scan
Tools are categorized one by one according to dependent variants,
debugCompileClassPath
Just
dedug
The dependency package in the packaging is
as above, it is more convenient and concise to analyze the dependency tree in this way

2. Use loop optimization
Gradle
Dependency management

As shown below, we often use

ext
To manage dependencies

dependencies { implementation fileTree( include: [ '*.jar' ], dir: 'libs' ) implementation rootProject.ext.dependencies[ " appcompat -v7" ] implementation rootProject.ext.dependencies[ "cardview-v7" ] implementation rootProject.ext.dependencies[ "design" ] implementation rootProject.ext.dependencies[ "constraint-layout" ] annotationProcessor rootProject.ext.dependencies[ "glide_compiler" ] ... } Copy code

Although this achieves unified management of dependencies, as the project becomes larger and larger, there will be more and more dependencies, often with dozens or even hundreds of lines, resulting

build.gradle
Getting longer

Is there a good way to be absent

build.gradle
Write so many dependency configurations?
Yes, it uses a loop to traverse the dependencies.
The example is as follows, first add
config.gradle

ext{ dependencies = [ //base "appcompat-v7" : "com.android.support:appcompat-v7:${version[" supportLibraryVersion "]}" , ... ] annotationProcessor = [ "glide_compiler" : "com.github.bumptech.glide:compiler:${version[" glideVersion "]}" , ... ] apiFileDependencies = [ "launchstarter" : "libs/launchstarter-release-1.0.0.aar" ] debugImplementationDependencies = [ "MethodTraceMan" : "com.github.zhengcx:MethodTraceMan:1.0.7" ] ... implementationExcludes = [ "com.android.support.test.espresso:espresso-idling-resource:3.0.2" : [ 'com.android.support' : 'support-annotations' ] ] ... } Copy code

Then in

build.gradle
The configuration is as follows:

apply from config.gradle ... def implementationDependencies = project.ext.dependencies def processors = project.ext.annotationProcesso def implementationExcludes = project.ext.implementationExcludes dependencies{ //Handle all xxximplementation dependencies implementationDependencies.each {k, v -> implementation v} //Handle annotationProcessor dependencies processors.each {k, v -> annotationProcessor v} //Process all dependencies that include exclude implementationExcludes.each {entry -> implementation(entry.key) { entry.value.each {childEntry -> exclude( group: childEntry) } } } ... } Copy code

The advantages of this are
1. Subsequent addition of dependencies does not require changes

build.gradle
, Directly at
config.gradle
Just add it in
2. It's streamlined
build.gradle
length

3. Support code hints
Gradle
Dependency management

Introduced above

config.gradle
The way to manage dependencies is
added in us
Gradle
There are still some pain points when relying on
1. Code prompt is
not supported 2. Click to jump is not supported
3. When multi-module development, the same dependencies of different modules need to be copied and pasted

use

buildSrc
+
kotlin
Can solve this problem
effect is as follows:

As the
buildSrc
Is all to the whole
module
Configuration, so it can be in all
module
Directly used in

Not much introduction here, detailed development and introduction

buildSrc
The process can be seen:
[Translation] Kotlin + buildSrc: better management of Gadle dependencies

buildSrc
vs
includeBuild

The method described above uses

buildSrc
,
It s more convenient to use, but its disadvantage is that the build speed will be slower. Use
includeBuild
The same effect can be achieved.
The final results achieved by the two are similar. The
detailed implementation can be seen: [Wonderful skill] In addition to buildSrc, can you also configure the dependent version in this way? Clever use of includeBuild

4.
Gradle
Modular

In our development, when we introduce some plug-ins, sometimes we need to

build.gradle
Introduce some configuration, such as
greendao
, Push,
tinker
Etc.
These can actually be encapsulated in the corresponding
gradle
File, and then pass
apply from
Introduce
, for example, when we use
greendao
Database, you need to
build.gradle
Version specified in

In this case, you should create a new one

greendao-config.gradle

apply plugin: 'org.greenrobot.greendao' //greenDao specifies the version and road King, etc. greendao { //The schema version of the database can also be understood as the database version number schemaVersion 1 //Set the DaoMaster, DaoSession, and Dao package names, that is, the full path of the packages where these classes are to be placed. daoPackage'com.example.ausu.big_progect.dao ' //Set DaoMaster, DaoSession, Dao directory targetGenDir'src /main/java' } Copy code

And then again

build.gradle
Introduced in

from Apply 'greendao-config.gradle' duplicated code

This has two main advantages:
1. The single responsibility principle will

greendao
The related configuration is encapsulated in one file, not to be confused with other files
2. Simplified
build.gradle
The code, and subsequent modifications to the database do not need to be modified
build.gradle
The code

5.
Library
Module
Gradle
Code reuse

As our project gets bigger and bigger,

Library Module
Also build more and more, each
Module
Have their own
build.gradle

But actually each
build.gradle
The contents are almost the same, can we encapsulate the repeated parts for reuse?

We can make a

basic
Extract, also extract the common parameters/information to
basic.gradle
In each
module
apply
, This is to reduce the amount of code a lot

apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { //Specify the API level used to compile the project compileSdkVersion Versions.compileSDK //Specify the SDK tool version to be used when generating the project. Manual configuration is not required after Android Studio 3.0. buildToolsVersion Versions.buildTools //Specify the default value of the version attribute of the Android plug-in applicable to all build versions defaultConfig { minSdkVersion Versions.minSDK targetSdkVersion Versions.targetSDK versionCode 1 versionName "1.0" } //Configure Java compilation (coding format, compilation level, generated bytecode version) compileOptions { encoding = 'utf-8' sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8.toString() } lintOptions { //Continue to execute abortOnError after lint exception false } } dependencies { implementation fileTree( dir: 'libs' , include: [ '*.jar' ]) ... } Copy code

Then in the corresponding module

build.gradle
Can be introduced in

apply from: "../basic.gradle" dependencies { api Deps.constraintLayout api Deps.retrofit } Copy code

Isn't this much more concise? Readers can judge whether it is suitable for extraction according to the actual situation of the project

basic.gradle
use

6. Resource file subcontracting

As the project gets bigger and bigger, the resource files in the project also get bigger and bigger, such as

layout
versus
drawable
The number of files in a folder can often reach hundreds or even thousands.
Can we subcontract resource files like code?

The answer is yes, mainly by using

gradle
of
sourceSets
Properties
We can subcontract resource files by business like code, the specific operations are as follows

1. Create a new directory res_xxx
in

main
Create a new directory
res_core
,
res_feed
(Named according to the business module) and other directories, in
res_core
New in
res
The same folder in the directory such as:
layout
,
drawable-xxhdpi
,
values
Wait.

2. In

gradle
Medium configuration
res_xx
table of Contents

android { //... sourceSets { main { res.srcDirs( 'src/main/res' , 'src/main/res_core' , 'src/main/res_feed' , ) } } } Copy code

The above completes the subcontracting of resource files. There are several advantages to doing this
. 1. It is convenient to find by business subcontracting, and the structure is clear
2.

strings.xml
Wait
key-value
Multi-person modification of type files can reduce conflicts
. 3. It is convenient to delete or migrate resource files when deleting modules or doing component transformation, so you don t have to look for them one by one as before.

7.
AAR
Quick switch between dependency and source code dependency

When our project

Module
More and more, in order to speed up the compilation, often put
Module
Publish into
AAR
, And then directly depend on the project
AAR

But we sometimes need to modify
AAR
, We need to rely on the source code,
so we need a system that can quickly switch dependencies
AAR
And rely on source code

Let s take an example below to

retrofit
For example,
if we want to modify
retrofit
The source code, the modification steps are as follows:
1. First download
retrofit
, Can be placed in the same level directory as the project, and modify the directory name
retrofit-source
In order to distinguish
2.
settings.gradle
Add the files that need to be modified
aar
Library source code
project

the include ': Retrofit-Source' Project ( ': Retrofit-Source' ) = .projectDir new new File ( "../retrofit-source" ) copy the code

3. Replace

aar
As source code
build.gradle(android)
Add replacement strategy in script

allprojects { repositories { ... } configurations.all { resolutionStrategy { dependencySubstitution { substitute module( "com.squareup.retrofit2:retrofit" ) with project( ':retofit-source' ) } } } } Copy code

The above steps can be implemented more conveniently

aar
Dependency and source code dependencies are interchanged
. The main advantages of this are
1. No need to modify the original dependency configuration, but replace it with the local source code through the global configuration
aar
, Low invasiveness
2. If there are multiple
Module
Depend on the same
aar
, No need to modify repeatedly, just in the root directory
build.gradle
Edit one in

summary

This article mainly introduces several practical

Gradle
Tips, if you find it helpful, you can give me a thumbs up.
If you find any shortcomings in this article, please point it out in the comment area~

Reference

Gradle Scan use introduction,
use cycle to optimize
Android refactoring | Continuous optimization and unified management of Gradle
Android res resource subcontracting