Recently I have been developing some Android projects. Each application has had the requirement to retrieve data from an on-line web server and, since I have been using the Volley library, I’ve had to copy my wrapper code into each project. Additionally I’ve had to copy the same GSON code to parse this data. This is of course time consuming and not a good approach to programming.
Another more sensible approach is to create a library that contains the required methods.
So, in this post let’s look at how to do that:
1) Launch Android Studio and create a new project, give it a sensible name, such as ‘MathsLibrary’ and choose ‘No Activity’ when prompted.
2) We now have a standard Android application project. This is no good as that’s what we’d use to generate an Android Application. We however wish to generate an Android library or, in fact an Android Archive (AAR).
3) To change this to a library:
- Open the app’s build.gradle file and change the line
apply plugin: 'com.android.application'
apply plugin: 'com.android.library'
4) Delete the applicationId line from the DefaultConfig section of build.gradle
5) Click ‘Sync Now‘
You’ve now created an empty library 🙂
6) Navigate to your src directory and then add a ‘Math’ class.
7) Add functions to add, subtract and multiply.
8) Click build and your library should build without any errors.
9) Now you’ve built a ‘debug’ library but it’s a ‘release’ library you should be building
10) Click on Build and then change the Build Variant to release.
11) Rebuild the project.
12) Now choose Build APK.
13) Since we aren’t building an app, Android Studio won’t generate an APK, it will instead generate a file entitled app-release.aar which can be found in the ‘app\build\outputs\aar‘ directory.
If you want to know how you can use this library in a project, click to read the next post.
Sample code for this blog post can be found on my GitHub: