Writing Android applications in .NET with Xamarin
Xamarin's main goal is to allow writing Android and iOS application using .NET languages and tools. Xamarin provides necessary tools to write, run, test, debug and publish your app on either Android or iOS devices without leaving Visual Studio environment.
In this article I’ll focus on Android development, describe how Xamarin achieves its goals and present simple code example.
How is the code usually run on Android?
Before we start talking about Xamarin, let’s briefly look at how code is usually run on Android devices:
Android is based on Linux kernel. Because of that it’s possible to write native code directly against the OS, but most developers work and interact with it by writing Java code. Android is shipped with its own Virtual Machine – the Android Runtime (“ART”).
Through ART APIs developers can work with every aspect of mobile device – user interface, storage, sensors, contacts and other system services.
How to introduce .NET into the picture?
Android is built on Linux kernel and there’s a project that allows to run .NET code on Linux – the Mono Project.
Using Mono, it should be possible to run Mono runtime on Android and to use it to run .NET’s IL instructions:
We’re missing one thing however – most of the functions needed to write modern applications are exposed through ART APIs, not the Android kernel. If we use other runtime, we lose access to those functions.
Xamarin mitigates this by running both Mono and ART side by side and providing mechanisms to expose needed APIs.
This approach allows to use exactly the same APIs as any other ART application, giving access to the same UI elements, sensors data and any other services.
However, there’s a significant cost connected – we’re now running two independent virtual machines, each one with its own execution model, managing its own memory and running its own garbage collection. In most cases we don’t have to worry about it but when we run into trouble (performance, memory leaks etc.) then, it’s important to understand what’s going on under the hood.
But Mono is not shipped with Android!
That’s true! Mono – together with a bootstrapper and some basic managed libraries – will be added to the application package during build process. This, of course, increases the size of the package, which can be especially visible for small applications:
Size overhead caused by Mono can be slightly reduced by using Xamarin’s “Linking” mechanism, which will remove unused code.
Example: Port list sample from Android SDK
To get a feeling of how it’s to code with Xamarin, let’s try to implement one of the Android SDK Java samples:
[table id=15 /]
The code is almost identical – most of the differences come from classes and constants being named accordingly to.NET conventions.
To verify whether code works, I used Visual Studio Android Emulator, which uses Hyper-V and Android x86 images: