Mediterranean Sea in Catalonia. Photo by Erick Medina.

How to add an Android AAR library in Kotlin Multiplatform?

Erick Medina
3 min readSep 9, 2024

--

Recently while doing exploratory code around Kotlin Multiplatform (KMP), I came with an scenario that might be usual for people migrating from native (android/iOS) into KMP.

That scenario is the usage of native libraries in KMP. First question, is why would you use a native library in a multiplatform project? Easy answer is because you don’t have any other way in certain scenarios. Let’s talk about an app that uses native SDKs for Android and iOS apps to communicate with an external device via Bluetooth. If the SDK provider doesn’t provide you a KMP library, you’ll have to use both native SDK within the multiplatform app.

For this article we’ll only consider adding a simplistic native Android library (.aar) into an KMP app. Let’s get into it.

First let’s create with Android Studio a simplistic android library that calculates a sum of two values.

We create a class called AndroidLib with an unique function that makes the calculation.

class AndroidLib {

fun calculateSum(value1: Int, value2: Int) : Int {
return value1 + value2
}

}

Then, we make a build of the library in order to generate the .aar file.

We locate the .aar file and import it to an KMP app. For this sample we use a simple KMP app with a composeApp module that contains the UI and the business logic.

We must create a new directory at the root level of composeApp called libs where we place the .aar file. It is important to note that we should add it at the root and not within the androdMain subdirectory, as we might be tempted to do.

Now we need to add the library to the build gradle file of the composeApp module. Here is where we indicate that this library should be consumed from within the Android module of the KMP app.

androidMain.dependencies {
...
implementation(files("libs/androidlib-debug.aar"))
...
}

After a successful gradle build, we are able to use the library in the code. In this case we’ll use it directly from the MainActivity.

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
val result = AndroidLib().calculateSum(value1 = 10, value2 = 50)
Log.d("Lib", "result: $result")
...
}
}

This way we can use an Android library in a Kotlin Multiplatform app. Take into consideration that an Android library can only be used within the androidMain submodule of our composeApp.

In our following article we’ll explore how to add an iOS library into KMP. Stay tuned!

--

--

No responses yet