Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an Android library aar as a module with Android Studio Arctic Fox?

I used to be able to import library aar files as modules and they have been working perfectly. I cannot figure out how to do it with Android Studio Arctic Fox, its latest version. Could anyone offer a tip on it?

I can follow the official instructions to add an aar as a dependency by adding the following in build.gradle:

implementation files('libs/myLibrary-release.aar')

Unfortunately, this will require the dependent app (i.e., the app that uses the above line in its build.gradle to use the library) to know which external libraries are used by myLibrary and add all the dependencies too. For example, if myLibrary has 30 dependencies such as "implementation 'joda-time:joda-time:2.10.5'", every dependent app will have to have these 30 dependencies. If myLibrary updates with a new dependency, all the dependent apps will need to add it too. The worst thing is the app can build and start fine without these dependencies but will crash at runtime when a missing dependency is needed.

like image 512
Hong Avatar asked Aug 04 '21 18:08

Hong


People also ask

How do I import a library module?

Import a module Click File > New > Import Module. In the Source directory box, type or select the directory of the module(s) that you want to import: If you are importing one module, indicate its root directory.


1 Answers

I recommend embedding all of myLibrary‘s dependencies inside myLibrary’s AAR file.

Embedding is quite easy - download all of the AARs and JARs of all of myLibrary’s dependencies, save them in lib folder and add the new local dependencies in the form of:

implementation files('libs/some-dependency.jar')

You do need to worry about duplicate class definitions in the app that consumes your AAR. For example, if you usejoda-time library and your consumer also use joda-time, the consumer’s build will fail because joda-time library is compiled twice.

The solution is to shadow your dependencies by changing all classes’ class path to a unique class path which cannot collide with you consumer app’s dependencies.

For example, class org.joda.time.DateTime will be transformed to just.a.unique.prefix.org.joda.time.DateTime.

I’ve seen shadowing in action, but I’m lack of experience with it. But check out the following guide to help you out: https://imperceptiblethoughts.com/shadow/

like image 53
Shlomi Katriel Avatar answered Sep 28 '22 21:09

Shlomi Katriel