A method in the Android project that references a local aar file

  • 2020-06-15 10:13:40
  • OfStack

As more and more projects grow, code reuse becomes extremely important, and this is where modular programming comes in, where 1 common component or library is made into a single module that is directly referenced by other projects. The most common way to develop for Android is Android Library. It is cumbersome to refer to Android Library before Gradle appeared, but with Gradle1 the shear is very simple and convenient.

aar

What is a aar? jar file is known to all, if you have a Android Library projects, can be easily exported jar file, and then very convenient reference in other projects, aar and jar similar, the difference is 1 Android Library project jar export file cannot contain resource files, such as 1 some drawable files, xml resources, such as so that there is a lot of limit, Before gradle, Android Library had to import the entire library for reference, but with gradle, the Android Library project can be exported directly to aar, and other projects can refer to jar directly.

Export aar

First, the gradle script for the Android Library project only needs to be declared at the beginning


apply plugin: 'com.android.library'

Perform./gradlew assembleRelease as you would export the apk file, then generate the aar file in the build/outputs/aar folder

Refer to 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 the jar file, and there is no official solution. Fortunately, some foreign predecessors have summed up the method. The following is an example of ES61en.aar to detail the method

1. Put aar files in one file directory, such as libs

2. Add the following to build. gradle file of app


repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

3. After that, add a sentence of gradle dependency to other items to conveniently reference the library

dependencies {
    compile(name:'test', ext:'aar')
}

The above method is effective.

conclusion

, of course, through the most common method is to put the aar gradle upload mavenCentral or jcenter, quote more convenient, but for some internal library 1 don't want to open, the traditional way of citing library too trival, citing local aar files this way will be very convenient, right after the general library module only need to make it, whether to update or modify only need packaged into aar, then it is good to be used by other projects, it is to improve code reuse for Android development is a very effective means of 1.


Related articles: