In this article I will tell you how to create a library that uses other libraries and at the same time fit everything into one jar.
Suppose we are writing a library, it uses other libraries and, in particular, for example, the support library. If we used maven, then we simply added dependencies in the pom file and did not steam. But what if our library will be used by people who do not use build systems or use ant 'ohm?
We can put dependencies next to our jar. But then conflicts of libraries of different versions are inevitable, for example, if we use one version of the support library, and the application itself is different. Then you have to remove one of them with your hands.
')
You can go the other way, remember that jar is a regular zip file. We unpack all the dependencies, get the bytecode in the form of .class files, then compile the code of our library, put all the .class files in one place and collect jar from them. But if the application uses the same libraries as ours, then we get an error that there are two identical classes in the project.
To solve this problem, we use the jarjar utility. It renames all classes in the jar file. For example, support library - all classes are in the android.support.v4 package
Usage example:
java -jar jarjar.jar process <rulesFile> <inJar> <outJar> rulesFile - inJar, outJar -
Create a rule to rename the android.support.v4. * Classes to inner.android.support.v4. *
rule android.support.v4.** inner.android.support.v4.@1
and save to the file rules.txt
Run
java -jar jarjar.jar rules.txt android-support-v4.jar android-support-v4-renamed.jar
As a result, we got jar'ku with renamed classes. Next, we unpack all our dependencies with the renamed classes and compile. We receive library which contains all code necessary for execution.
Our library contains the code of all dependencies that can weigh a lot. To reduce the size, use proguard to remove unused classes and methods.
And finally, a small gradle script that does all this.
apply plugin: 'java' defaultTasks 'proguard' task unpackJars(dependsOn: compileJava) {
War and everything, after executing the script, we get proguard_library.jar, which can be added to the application and used.
In my case, the library uses the support library and dropbox sdk, and it weighs 50 kB.
In the same way, you can reduce the size of your apk, all dependencies can be connected not as jar files, but unpacked into .classes and use proguard, then it will remove unused classes from libraries. So you can connect to the project heavy frameworks without fear of increasing the size of apk