In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the practical skills of Gradle". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the practical skills of Gradle"?
1.Gradle dependency tree query
Sometimes when we analyze dependency conflicts, we need to look at the dependency tree. Our common command to view the dependency tree is
Gradlew app:dependencies
However, there is too much information from the dependent tree in this command-line way, and it is a bit difficult to read it.
So officials have launched the Scan tool to help us view the dependency tree more easily.
Run gradle build\-- scan in the root directory of the project, and then generate an analysis file in HTML format
The analysis file will be uploaded directly to the Scan official website, and the command line will finally give the remote address.
The first time you run will let you register on the official website of Scan, and you can read it after confirming your email.
The scan tool is classified by dependency variants, and debugCompileClassPath is the dependency package in the dedug package.
As mentioned above, it is more convenient and concise to analyze the dependency tree in this way.
two。 Using loops to optimize 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"].}
In this way, although the unified management of dependencies is achieved, as the project becomes larger and larger, there will be more and more dependencies, often with dozens or even hundreds of lines, resulting in build.gradle getting longer and longer.
Is there a good way not to write so many dependency configurations in build.gradle?
Yes, just use a loop to traverse 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']].}
Then configure it in build.gradle 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} / / handle all exclude dependencies implementationExcludes.each {entry-> implementation (entry.key) {entry.value.each {childEntry-> exclude (group: childEntry)}.}
The advantage of this is that
1. You don't need to change the build.gradle to add dependencies later, just add them in config.gradle.
two。 Simplified the length of build.gradle
3. Gradle dependency management supporting code hints
The method of managing dependencies through config.gradle is described above
When we add Gradle dependencies, there are some pain points
1. Code hints are not supported
two。 Click to jump is not supported
3. In multi-module development, the same dependencies of different modules need to be copied and pasted
Using buildSrc+kotlin can solve this problem.
The effect is as follows:
Because buildSrc is configured for all global module, it can be used directly in all module
Without much introduction here, the process of detailed development and introduction of buildSrc can be seen as follows:
Kotlin + buildSrc: better management of Gadle dependencies
BuildSrc vs includeBuild
The method described above uses buildSrc, which is easy to use.
However, its disadvantage is that it is slower to build, and the same effect can be achieved with includeBuild.
The final effect of the two is similar.
The detailed implementation can be seen as follows: in addition to buildSrc, can you also configure the dependent version in such a unified way? Skillful use of includeBuild
4.Gradle modularization
In our development, when we introduce some plug-ins, we sometimes need to introduce some configurations in build.gradle, such as greendao, push, tinker, etc.
These can actually be encapsulated in the corresponding gradle file and then introduced through apply from
For example, when we use a greendao database, we need to specify a version in build.gradle
A new greendao-config.gradle should be created at a time like this.
Apply plugin: 'org.greenrobot.greendao' / / greenDao specifies the schema version of greendao {/ / database such as Lujin. It can also be understood as the database version number schemaVersion 1 / / which sets the package name of DaoMaster, DaoSession, and Dao, that is, the full path of the package where these classes are to be placed. DaoPackage 'com.example.ausu.big_progect.dao' / / set DaoMaster, DaoSession, Dao directories targetGenDir' src/main/java'}
And then introduce it into build.gradle
Apply from 'greendao-config.gradle'
There are two main advantages to doing so.
1. The principle of single responsibility, encapsulating the relevant configuration of greendao in a file and not confusing it with other files
two。 The code of build.gradle is simplified, and there is no need to modify the code of build.gradle when modifying the database later.
Gradle code reuse of 5.Library module
As our project gets bigger and bigger, more and more Library Module are built, and each Module has its own build.gradle.
But in fact, the content of every build.gradle is the same, can we encapsulate the repeated parts and reuse them?
We can do a basic extraction, and also extract the common parameters / information into the basic.gradle, each module apply, which reduces a lot of code.
Apply plugin: 'com.android.library' apply plugin:' kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin:' kotlin-kapt' android {/ / specifies the API level compileSdkVersion Versions.compileSDK / / used to compile the project, specifies the version of the SDK tool to be used when building the project, and does not require manual configuration after Android Studio 3.0. BuildToolsVersion Versions.buildTools / / specifies the default value of the Android plug-in's version properties for all builds: defaultConfig {minSdkVersion Versions.minSDK targetSdkVersion Versions.targetSDK versionCode 1 versionName "1.0"} / / configure Java compilation (encoding format, compilation level, Generate bytecode version) compileOptions {encoding = 'utf-8' sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8} kotlinOptions {jvmTarget = JavaVersion.VERSION_1_8.toString ()} lintOptions {/ / lint exception and continue to execute abortOnError false} dependencies {implementation fileTree (dir:' libs') Include: ['* .jar']).}
Then introduce it into the build.gradle of the corresponding module.
Apply from: ".. / basic.gradle" dependencies {api Deps.constraintLayout api Deps.retrofit}
Isn't that much simpler? Readers can judge whether it is suitable to extract basic.gradle according to the actual situation of the project.
6. Resource file subcontracting
As the project becomes larger and larger, so do the resource files in the project. For example, the number of files under the layout and drawable folders can often reach hundreds or even thousands.
Can we subcontract resource files like code?
The answer is yes, mainly using the sourceSets attribute of gradle
We can subcontract resource files by business like code, as follows
1. Create a new res_xxx directory
Create new directories such as res_core and res_feed (named according to the business module) under the main directory, and create the same folders in the res directory in res_core, such as layout, drawable-xxhdpi, values, etc.
two。 Configure the res_xx directory in gradle
Android {/ /... SourceSets {main {res.srcDirs ('src/main/res',' src/main/res_core', 'src/main/res_feed',)}
The above completes the resource file subcontracting, which has several main benefits
1. It is convenient to find by business subcontract and the structure is clear.
Multi-person modification of key- value files such as 2.strings.xml can reduce conflicts
3. When deleting modules or doing component transformation, it is convenient to delete or migrate resource files, so you don't have to look for them one by one as before.
Fast switching between 7.AAR dependency and source code dependency
When there are more and more Module in our project, in order to speed up the compilation, we often publish Module as AAR, and then rely on AAR directly in the project.
But sometimes we need to modify the AAR, so we need to rely on the source code
So we need a way to quickly switch between relying on AAR and relying on source code.
Let's give an example, take retrofit as an example.
If we want to modify the source code of retrofit, the steps are as follows:
1. First download retrofit, you can put it in a directory at the same level as the project, and change the directory name to retrofit-source to distinguish
two。 Add the source project of the aar library that needs to be modified in the settings.gradle file
Include': retrofit-source' project (': retrofit-source'). ProjectDir = new File (".. / retrofit-source")
3. Replace aar with source code
Add replacement policy to build.gradle (android) script
Allprojects {repositories {...} configurations.all {resolutionStrategy {dependencySubstitution {substitute module ("com.squareup.retrofit2:retrofit") with project (': retofit-source')}
As in the previous steps, the interchange between aar dependencies and source code dependencies can be easily realized.
The main advantage of this is that
1. There is no need to modify the original dependency configuration, but through the global configuration, the local source code is used to replace aar, which is less intrusive.
two。 If more than one Module depends on the same aar, you don't need to modify it repeatedly, just modify one place in the root directory build.gradle.
Thank you for your reading, these are the contents of "what are the practical skills of Gradle". After the study of this article, I believe you have a deeper understanding of the practical skills of Gradle, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.