I have an Android application that dynamically loads a library using DexClassLoader
. Until now the application and the library were developed in separate projects. I would like to unite the projects into a single project (two modules in a project?) but I am not sure how to achieve it with Android Studio/Gradle. Note, that I don't want to add a static dependency between the app and the library. The result I want to achieve is:
Any ideas?
Xiaomi's answer gave a good direction, but the eventual solution was somewhat different.
The project is going to contain two modules: one for the application and one for the library. The app module will depend on the library so the library will be built before the app. When the JAR file is ready, it will be converted into DEX and copied into the app's assets library. The build activity of the application will automatically bundle the assets folder in the final APK.
If it isn't already there, include the library module in the project settings file settings.gradle
:
include ':app', ':libmynewlibrary'
Add the dependency in the build.gradle
of app
module:
dependencies {
...
compile project(':libmynewlibrary')
}
Now the tricky part. We want to add a custom action immediately after the JAR is created. Luckily Android Gradle plugin has a predefined task "jar" - it builds the JAR obviously. We will just add something to it in the lib's build.gradle
. Notice that the task is implicit and isn't in the gradle file at all. We are just expanding it by adding doLast
to it:
jar {
doLast {
exec {
executable "dx"
args "--verbose", "--dex", "--output=../app/src/main/assets/mynewlib.dex", "build/libs/libmynewlib.jar"
}
}
}