To use Android native Kotlin code in a .NET MAUI app, you need to bridge between the two worlds—.NET (C#) and the Android Java/Kotlin world. In .NET MAUI, this is possible on Android using the Java Native Interface (JNI) or by creating a Java/Kotlin library (AAR) and binding it via a Binding Library.
Example: Using Kotlin in a .NET MAUI App (Android)
Goal: Call a Kotlin function from a .NET MAUI app on Android.
Step 1: Create a Kotlin Library (AAR)
Use Android Studio to create a Kotlin library:
MyKotlinLibrary.kt
Build the AAR:
-
Go to
Build > Make Module 'mykotlinlibrary'
. -
The AAR file is located in
build/outputs/aar/mykotlinlibrary-release.aar
.
Step 2: Create a .NET MAUI Android Binding Library
In your MAUI solution:
-
Right-click on the solution →
Add > New Project
. -
Choose Android Bindings Library.
-
Name it something like
MyKotlinBinding
.
Add the AAR file:
-
Add the AAR to the
Jars
folder (create it if needed). -
Right-click →
Build Action
→LibraryProjectZip
.
Example Directory:
Now build the binding project. It will auto-generate C# bindings to the Kotlin class.
Step 3: Use the Kotlin Code in Your .NET MAUI App
In your .NET MAUI app project:
-
Add a project reference to the
MyKotlinBinding
library.
Then, you can access the Kotlin class:
Example: MainPage.xaml.cs
Output
On Android, when you run the app, you'll see in the logs or debugger:
π§ Notes
-
The Kotlin class must be public, and its methods should not be
inline
orinternal
. -
If the Kotlin code uses Kotlin-only features like coroutines or default parameters, you may need extra configuration in your binding project.
No comments:
Post a Comment