When developing an Android application, we can generate an AAR file and use it in different android projects.
Creating an Android Library will save you time compiling and running your project, and you can share existing services, images, resources, layouts with other people.
As you build your library, remember this quote:
“If you wish to make an apple pie from scratch, you must first invent the universe.” ― Carl Sagan, Cosmos
So let’s get started.
Starting process:
This would create an empty Android project.
Click File > New > New Module.
In the Create New Module window that appears, click Android Library
Then give your library a name and select a minimum SDK version for the code in the library, then click Finish.
The library module appears in the Project panel on the left.
At the top of the file, you should include the following line if it is not already there.
apply plugin: 'com.android.library'
~/woah/build.gradle
plugins {
id 'org.jetbrains.kotlin.android'
id 'com.android.library'
}
android {
compileSdk 31
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
}
Try to simply Build > Rebuild project or execute in terminal:
./gradlew assembleRelease
or choose assembleRelease
from Android Studio's Gradle menu.
After a successful build, First switch to the project view in the left panel and navigate as sown below.
AAR file should appear in ~/woah/build/outputs/aar/
AAR files can contain Android resources and a manifest file, which allows you to bundle in shared resources like layouts and drawables in addition to Java classes and methods.
AAR files can contain C/C++ libraries for use by the app module's C/C++ code.
Let’s write a simple library that is shown when your app gets crashed.
interface CrashListener {
fun onUncaughtException(thread: Thread, throwable: Throwable)
}
object Woah {
@JvmStatic
fun init(crashListener: CrashListener) {
Thread.setDefaultUncaughtExceptionHandler { p0, p1 ->
crashListener.onUncaughtException(p0, p1)
}
}
}
Adding @Keep on a class protects the class from removing by proguard during optimization.
Don’t use default resource names such as colorAccent
or colorPrimary
in resources.
Default host app resources will always be prioritized.
Just move the AAR file to the libs directory.
Then add in build.gradle
file:
dependencies {
implementation project(':woah')
implementation fileTree(dir: "libs", include: ["*.aar"])
...
}
In this guide, we have covered all the steps you need to take to create an Android Library.
The goal of creating an Android Library should be to develop more user-friendly interfaces that can be reused.
Sample (full code)
https://github.com/tkrest/woah
Android-library
https://developer.android.com/studio/projects/android-library
Dependencies
https://developer.android.com/studio/build/dependencies