As more and more projects are needed, code reuse becomes extremely important. At this time, modular programming is necessary, which means to make some general components or class libraries into separate modules, and other projects are referenced directly. The most common thing for Android development is Android Library. The way to quote Android Library before Gradle appeared was also very cumbersome, but with Gradle everything becomes very simple and convenient.
aar
What is aar? Everyone knows jar file. If you have an Android Library project, you can easily export the jar file and then easily reference it in other projects. Aar is similar to jar. The difference is that a jar file exported by an Android Library project cannot contain resource files, such as some drawable files, xml resource files, etc., so this has great limitations. Before gradle, we must import the entire library to reference it. However, with gradle, the Android Library project can be directly exported into aar, and other projects can be directly and conveniently referenced like referencing jars.
Export aar
First of all, the gradle script of the Android Library project only needs to be declared at the beginning
apply plugin: ''
Then, the same method as exporting the apk file, execute ./gradlew assembleRelease, and then you can generate aar file in the build/outputs/aar folder
Quoting local aar
After generating aar, the next step is how to reference the local aar file? The local aar file is not as simple as referencing a jar file, and the official has not provided a solution. Fortunately, some foreign seniors have summarized the method, so let’s take the document as an example to describe the method in detail.
1. Put the aar file in a file directory, for example, in the libs directory
2. Add the following content to the app file
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
3. Then add a gradle dependency to other projects to easily quote the library
dependencies {
compile(name:'test', ext:'aar')
}
The above method is effective in personal testing.
Summarize
Of course, the most common method of gradle is to upload aar to mavenCentral or jcenter. Quotation is more convenient, but for some companies, the internal library does not want to be disclosed, and the traditional way of quoting library is too cumbersome. It will be very convenient and suitable to quote local aar files. After that, the general module only needs to be made into a library. Whether it is updated or modified, it only needs to be packaged into aar, and then used by other projects. For Android development, this is a very effective way to improve code reuse.