Android development modular programming reference local aar

With more and more projects, the reuse of code becomes extremely important. At this time, modular programming is necessary, that is, some common components or class libraries are made into separate modules, and other projects can be directly referenced. The most common for Android development is Android Library. The way to reference Android Library before Gradle appeared was also very cumbersome, but with Gradle everything became very simple and convenient.

aar

What is aar? Everyone knows the 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 the jar file exported by an Android Library project cannot contain it. Resource files, such as some drawable files, xml resource files, etc., so this has great limitations. Before gradle, we have to reference the Android Library with resource files. We must import the entire library for reference, but with gradle After that, the Android Library project can be directly exported as aar, and then other projects can be directly and conveniently referenced like jar.

Export aar

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

apply plugin: 'com.android.library'

After that, execute ./gradlew assembleRelease in the same way as exporting apk files  , and then you can  generate aar files in the  build/outputs/aar folder

Reference local aar

After generating the 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 the official does not provide a solution. Fortunately, some predecessors abroad have summarized the method, the following will take the test.aar file as an example to describe the method in detail

1. Put the aar file in a file directory, such as in the libs directory

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

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 reference the library

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

以上方法亲测有效。

总结

当然通过gradle最普遍的方法是把aar上传到mavenCentral或者jcenter,引用的话更方便,但是对于一些公司内部library不想公开,而传统的引用library方式又太繁琐,引用本地的aar文件这种方式会非常方便合适,之后通用的模块只需要做成library,不管更新还是修改只需要打包成aar,然后供其他项目使用就好了,对Android开发来说这是提升代码复用非常有效的一个手段。

Guess you like

Origin blog.csdn.net/xhf_123/article/details/50015299