Friday, 1 August 2025

Using Kotlin in a .NET MAUI App (Android)

 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

package com.example.mykotlinlib class MyKotlinHelper { fun greet(name: String): String { return "Hello from Kotlin, $name!" } }

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:

  1. Right-click on the solution → Add > New Project.

  2. Choose Android Bindings Library.

  3. Name it something like MyKotlinBinding.

Add the AAR file:

  • Add the AAR to the Jars folder (create it if needed).

  • Right-click → Build ActionLibraryProjectZip.

Example Directory:

MyKotlinBinding/ └── Jars/ └── mykotlinlibrary-release.aar

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

#if ANDROID using Com.Example.Mykotlinlib; // Namespace auto-generated from the Kotlin AAR #endif ... public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); #if ANDROID var helper = new MyKotlinHelper(); string message = helper.Greet("MAUI Developer"); Console.WriteLine(message); // Output: Hello from Kotlin, MAUI Developer! #endif } }

Output

On Android, when you run the app, you'll see in the logs or debugger:

Hello from Kotlin, MAUI Developer!

πŸ”§ Notes

  • The Kotlin class must be public, and its methods should not be inline or internal.

  • 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

Cricket Streaming MAUI App: Complete Solution

This document outlines a comprehensive solution for building a cricket streaming MAUI app with subscription plans, geo-restrictions, and pre...

Ads2