What is a Library?
What does a “library” mean in programming world?
“ A library is a precompiled code and resources that can be used in other projects easily “
In Android, mainly two types of libraries are used: JAR and AAR.
What is JAR:
Full form of JAR is Java Archived. A JAR file is a Zipped formatted file with .jar extension, containing Java Class files, metadata and other resources like text, images etc. JAR files may also contain one Manifest.MF file. This file contains information like which Java class is the entry point, classpaths etc.
What is AAR:
Android Archive or AAR files allows you to contain not only the source class files but also other resources, permissions, assets etc. we use in Android Projects. AAR file contains the following mandatory entries:
- /AndroidManifest.xml
- /classes.jar
- /res/
- /R.txt
It may also include one or more of the following entries:
- /assets/
- /libs/lib_name.jar
- /jni/abi_name/bin_name.so
- /proguard.txt
- /lint.jar
Build a library:
Create a JAR in Android Studio:
Select File -> New -> New Module and select “Java Library” from the selection :
Click Next -> Finish
It will create a new java library project.
But you cannot add any android Framework dependency in this library.
How to create a library for android then? Simply select “Android Library” instead of “Java Library” in the last step above . done !!
But how to get the .jar file for both of these libraries?
For “Java Library”, use ./gradlew build to create .jar . Output file will be inside /build/libs/ folder.
For “Android Library”, we will have to use one custom Gradle task:
Copy-paste the following code snippet inside build.gradle file:
task deleteJar(type : Delete){ delete 'libs/myLib.jar' } task createJar(type : Copy){ from ('build/intermediates/bundles/release/') into ('libs') include ('classes.jar') rename ('classes.jar','myLib.jar') } createJar.dependsOn(deleteJar,build)
Now use the command ./gradlew createJar to build the jar. The output file will be inside /yourLibrary/libs/ folder.
Create an AAR in Android Studio:
Generating an AAR is easier than jar. Just use “./gradlew assembleRelease” and it will generate release AAR inside /yourLib/build/outputs/aar/ folder.
Use AAR or JAR file in Android Studio:
JAR :
add the following line inside dependencies {} tab of build.gradle
compile files(‘libs/myJarLib.jar’)
myJarLib.jar should be inside ‘libs’ folder.
AAR :
Add the following inside dependencies {} tab :
compile(name:”myAarLib” ,ext : ‘aar’)
and ( not inside dependencies{})
repositories{ flatDir{ dirs 'libs' } }
Rebuild the project and it should work.
– Nandan