Reputation: 6790
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?
Upvotes: 1
Views: 1939
Reputation: 6790
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"
}
}
}
Upvotes: 1
Reputation: 6703
If you want to bring your module into your project, you can edit in your project the file settings.gradle
to include the module and to give its path.
include ':app' //your project module name
include ':library' //your imported module name
project(':library').projectDir = new File("/<path_to_module_library>/other_project/library")
Then the module will appear into your project.
If you go to your project gradle file (E.g.: build.gradle), you can now include your module as your project dependency.
dependencies {
...
compile project(':library')
...
}
Edit
If you just want to automatically copy your jar from your library to your project's assets folder, you can simply define a gradle task in your library build.gradle like :
task copyTask(type: Sync) {
from '/<path_to_your_jar>/classes.jar'
into '/<path_to_your_project>/app/assets/'
}
This will copy your jar to your assets folder.
To use it when you are compile your code, you can add this task into the Run/Debug Configuration.
Upvotes: 1