Creating Cross-Platform Apps with Xamarin: A Complete Guide for Modern Mobile Development

362 0 0 0 0

📘 Chapter 4: Working with Platform-Specific Features and Native APIs

🧭 What You’ll Learn

In this chapter, you will explore:

  • Accessing device hardware and native features in Xamarin
  • Using Xamarin.Essentials for common cross-platform features
  • Implementing platform-specific behavior using DependencyService
  • Writing and consuming custom renderers
  • Accessing platform APIs with native bindings
  • Sharing native capabilities without breaking UI abstraction
  • Debugging and maintaining cross-platform feature parity

By the end of this chapter, you’ll be able to unlock native power across Android and iOS without leaving your shared Xamarin.Forms project.


🧩 The Challenge of Platform-Specific Features

Xamarin.Forms is designed for maximum code reuse, but not every mobile platform behaves identically. You may encounter scenarios like:

  • Using the camera or GPS
  • Reading from the accelerometer
  • Handling native alerts, toasts, or notifications
  • Accessing OS-specific APIs like Face ID, Android Intents, etc.

Xamarin offers several tools to handle this without breaking cross-platform harmony.


🔧 Option 1: Xamarin.Essentials

Xamarin.Essentials is a library by Microsoft that wraps native APIs behind simple cross-platform APIs.

Installation

bash

 

Install-Package Xamarin.Essentials

Or in .csproj:

xml

 

<PackageReference Include="Xamarin.Essentials" Version="1.8.0" />

Initialization

  • Android: Add Xamarin.Essentials.Platform.Init(...) in MainActivity.cs
  • iOS: Add Xamarin.Essentials.Platform.Init() in AppDelegate.cs

🔑 Key APIs in Xamarin.Essentials

Feature

Example Method

Platforms

Geolocation

GetLocationAsync()

Android, iOS

Device Info

DeviceInfo.Model

Android, iOS

Secure Storage

SecureStorage.SetAsync()

Android, iOS

Connectivity

Connectivity.NetworkAccess

Android, iOS

Accelerometer

Accelerometer.Start()

Android, iOS

Browser

Browser.OpenAsync()

Android, iOS

Share

Share.RequestAsync()

Android, iOS

Vibration

Vibration.Vibrate()

Android, iOS


🔍 Sample: Get Device Location

csharp

 

using Xamarin.Essentials;

 

var location = await Geolocation.GetLastKnownLocationAsync();

if (location != null)

{

    Console.WriteLine($"Lat: {location.Latitude}, Long: {location.Longitude}");

}


🧩 Option 2: DependencyService for Platform-Specific Code

When Xamarin.Essentials doesn't cover your use case, use DependencyService to inject platform-specific implementations.


Step-by-Step Example

Goal: Use native vibration on Android only.


1️ Define Interface in Shared Project

csharp

 

public interface IDeviceVibrator

{

    void VibrateDevice();

}


2️ Implement in Android Project

MainActivity.cs or separate service class:

csharp

 

[assembly: Dependency(typeof(DeviceVibrator))]

namespace MyApp.Droid

{

    public class DeviceVibrator : IDeviceVibrator

    {

        public void VibrateDevice()

        {

            var vibrator = (Vibrator)Android.App.Application.Context.GetSystemService(Context.VibratorService);

            vibrator?.Vibrate(VibrationEffect.CreateOneShot(500, VibrationEffect.DefaultAmplitude));

        }

    }

}


3️ Call It in Shared Code

csharp

 

DependencyService.Get<IDeviceVibrator>()?.VibrateDevice();


🧬 Option 3: Custom Renderers

Custom renderers allow you to override the rendering behavior of Xamarin.Forms controls with platform-native views.

When to Use:

  • Customize how a control looks or behaves on Android/iOS
  • Add native effects, animations, or accessibility options
  • Integrate with native SDKs

🔍 Example: Custom Button Renderer

1️ In Shared Project

csharp

 

public class CustomButton : Button

{

    // You can add custom properties here if needed

}


2️ Android Renderer

csharp

 

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]

namespace MyApp.Droid.Renderers

{

    public class CustomButtonRenderer : ButtonRenderer

    {

        public CustomButtonRenderer(Context context) : base(context) { }

 

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)

        {

            base.OnElementChanged(e);

            if (Control != null)

            {

                Control.SetBackgroundColor(Android.Graphics.Color.Red);

                Control.SetAllCaps(false);

            }

        }

    }

}


3️ iOS Renderer

csharp

 

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]

namespace MyApp.iOS.Renderers

{

    public class CustomButtonRenderer : ButtonRenderer

    {

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)

        {

            base.OnElementChanged(e);

            if (Control != null)

            {

                Control.BackgroundColor = UIColor.Red;

            }

        }

    }

}


🔍 Platform Checks in Shared Code

You can conditionally run code based on platform using:

Device.RuntimePlatform

csharp

 

if (Device.RuntimePlatform == Device.Android)

{

    // Android-specific behavior

}


OnPlatform XAML Markup

xml

 

<Label Text="Welcome!"

       FontSize="{OnPlatform Android=18, iOS=20}" />


🔗 Using Native Bindings

You can create bindings to existing native libraries (e.g., Objective-C .framework, or Java .aar/.jar files) to use third-party native SDKs in your Xamarin app.

This process involves creating Binding Library projects in Visual Studio.


📱 Table: Summary of Native Feature Access Methods

Feature Type

Best Xamarin Approach

Device hardware access

Xamarin.Essentials

Custom native SDK

Binding libraries

Platform-specific logic

DependencyService

UI customization

Custom Renderers

Simple conditional behavior

Device.RuntimePlatform


Best Practices

  • Keep platform code isolated in DependencyService or Renderer files
  • Use Xamarin.Essentials where possible to reduce code complexity
  • Ensure you test each platform separately, especially with sensors or permissions
  • Use permissions APIs to check runtime access on Android 6.0+ and iOS
  • Don't over-customize—prefer shared UI unless a native experience is necessary

🧠 Example Use Cases and Matching Solutions


Use Case

Recommended Approach

Get battery level

Xamarin.Essentials

Access camera with custom overlay

Custom Renderer / Dependency

Handle fingerprint authentication

Xamarin.Essentials

Launch external email client

Xamarin.Essentials: Email.ComposeAsync()

Use native toast on Android

DependencyService

Render Google Maps natively

Custom Renderer or Plugin

Back

FAQs


❓1. What is Xamarin and how does it work?

Answer:
Xamarin is a Microsoft-backed open-source framework for building cross-platform mobile applications using C# and .NET. It allows developers to write shared business logic and optionally shared UI using Xamarin.Forms, while still accessing native APIs for iOS, Android, and Windows.

❓2. What is the difference between Xamarin.Forms and Xamarin.Native?

Answer:

  • Xamarin.Forms lets you write a single shared UI in XAML that runs on both Android and iOS.
  • Xamarin.Native (Xamarin.iOS and Xamarin.Android) provides full access to native UI APIs, meaning you must create platform-specific UIs but share backend code.

❓3. Can I build apps for iOS using Xamarin on Windows?

Answer:
Yes, but iOS apps must still be compiled on a Mac build host due to Apple’s restrictions. Visual Studio on Windows can remotely connect to a Mac to build and deploy iOS apps.

❓4. How much code can be shared between platforms in Xamarin?

Answer:
With Xamarin.Forms, you can share 90–95% of your code, including business logic and UI. With Xamarin.Native, you typically share 70–80%, with UI coded separately per platform.

❓5. Is Xamarin still relevant with .NET MAUI coming?

Answer:
Yes. Xamarin remains stable and supported, especially for existing projects. However, new projects are encouraged to use .NET MAUI, the evolution of Xamarin, offering broader platform support and modernized architecture.

❓6. Does Xamarin deliver native performance?

Answer:
Yes. Xamarin apps are compiled into native code (AOT on iOS, JIT on Android) and use native controls, which means the performance is on par with apps built using Swift, Kotlin, or Objective-C.

❓7. What programming language does Xamarin use?

Answer:
Xamarin uses C# as the primary programming language, supported by the .NET platform. You can also use XAML for defining UIs in Xamarin.Forms.

❓8. What tools are required to develop with Xamarin?

  • Visual Studio 2022 or later (with Mobile Development workload)
  • .NET SDK
  • Xamarin SDKs (included with Visual Studio)
  • Mac build machine (for iOS development)

❓9. Can I access device-specific features like camera or GPS?

Answer:
Yes. Xamarin provides bindings to native APIs, and Xamarin.Essentials offers cross-platform access to common features like camera, sensors, geolocation, battery, and connectivity with a unified API.

❓10. What are the alternatives to Xamarin for cross-platform development?

Answer:
Some popular alternatives include:

  • Flutter (Dart-based, Google)
  • React Native (JavaScript-based, Meta)
  • .NET MAUI (Xamarin’s successor, Microsoft)
  • Cordova/Capacitor (Web-based hybrid apps)

Each has its own pros and cons depending on the use case, team skills, and performance requirements.