MAUI Platform APIs

Accessing Device and Platform Features in .NET MAUI

Introduction to MAUI Platform APIs

.NET MAUI (Multi-platform App UI) provides a unified way to develop native mobile and desktop applications with C# and XAML. While MAUI offers a rich set of cross-platform UI controls and APIs, there are times when you need to access device-specific or platform-specific functionality that isn't directly exposed through the core MAUI abstractions.

This documentation guides you through accessing these platform APIs, ensuring your application can leverage the full capabilities of the underlying operating systems.

Platform-Specific Functionality

MAUI aims to abstract away platform differences where possible. However, unique hardware features (like specific sensors), OS services, or specialized UI elements may require direct interaction with platform-specific APIs.

MAUI provides mechanisms to achieve this, allowing you to write platform-conditional code or implement custom handlers for platform-specific behaviors.

Accessing Platform APIs

There are several ways to access platform-specific APIs in .NET MAUI:

  • Platform-Specific Projects: Each .NET MAUI project includes platform-specific projects (e.g., Android, iOS, Mac Catalyst, Windows). You can add native platform code directly within these projects.
  • Dependency Injection: MAUI's dependency injection system can be used to register platform-specific implementations of interfaces.
  • Microsoft.Maui.Essentials: A set of cross-platform APIs that abstract common device features. Many of these were previously part of Xamarin.Essentials.
  • Conditional Compilation: Use preprocessor directives like #if ANDROID, #if IOS, etc., to conditionally compile code for specific platforms.
Device Information >

Device Information

The Microsoft.Maui.Devices namespace provides access to information about the device your application is running on.

DeviceInfo

The DeviceInfo class provides properties related to the device's model, manufacturer, operating system, and more.

using Microsoft.Maui.Devices;

// Get device model
var deviceModel = DeviceInfo.Model;
Console.WriteLine($"Device Model: {deviceModel}");

// Get operating system version
var osVersion = DeviceInfo.VersionString;
Console.WriteLine($"OS Version: {osVersion}");

// Check if the device is a tablet
var isTablet = DeviceInfo.Idiom == Idiom.Tablet;
Console.WriteLine($"Is Tablet: {isTablet}");

Battery

The Battery class allows you to monitor the device's battery charge level and state.

using Microsoft.Maui.Devices;

// Get battery charge level
var chargeLevel = Battery.ChargeLevel;
Console.WriteLine($"Battery Level: {chargeLevel * 100}%");

// Get battery state
var batteryState = Battery.State;
Console.WriteLine($"Battery State: {batteryState}");

// Subscribe to battery change events
Battery.BatteryInfoChanged += (sender, args) =>
{
    Console.WriteLine($"Battery Info Changed - Level: {args.ChargeLevel * 100}%, State: {args.State}");
};

Connectivity

The Connectivity class allows you to check the device's network connectivity status.

using Microsoft.Maui.Connectivity;

// Get current network access
var networkAccess = Connectivity.NetworkAccess;
Console.WriteLine($"Network Access: {networkAccess}");

// Subscribe to connectivity change events
Connectivity.ConnectivityChanged += (sender, args) =>
{
    Console.WriteLine($"Connectivity Changed - Profiles: {args.Profiles}");
};

Orientation

The Orientation class provides information about the device's screen orientation.

using Microsoft.Maui.Devices;

// Get current orientation
var orientation = DeviceDisplay.MainDisplayInfo.Orientation;
Console.WriteLine($"Current Orientation: {orientation}");

// Subscribe to orientation change events
DeviceDisplay.MainDisplayInfoChanged += (sender, args) =>
{
    Console.WriteLine($"Orientation Changed - New Orientation: {args.Orientation}");
};
Sensors >

Sensors

.NET MAUI provides access to various device sensors, allowing you to capture motion, location, and environmental data.

Accelerometer

The Accelerometer class allows you to access the device's accelerometer to detect motion.

using Microsoft.Maui.Devices.Sensors;

if (Accelerometer.IsMonitoring)
{
    // Stop monitoring if already started
    Accelerometer.Stop();
}
else
{
    // Start monitoring accelerometer data
    Accelerometer.Start(SensorSpeed.UI); // Use SensorSpeed.UI for UI updates
    Accelerometer.ReadingChanged += (sender, args) =>
    {
        var data = args.Reading;
        Console.WriteLine($"Accelerometer - X: {data.Acceleration.X}, Y: {data.Acceleration.Y}, Z: {data.Acceleration.Z}");
    };
}

Compass

The Compass class allows you to access the device's magnetic compass.

using Microsoft.Maui.Devices.Sensors;

if (Compass.IsMonitoring)
{
    Compass.Stop();
}
else
{
    Compass.Start(SensorSpeed.UI);
    Compass.ReadingChanged += (sender, args) =>
    {
        Console.WriteLine($"Compass - Magnetic Field X: {args.Reading.MagneticField.X}");
        Console.WriteLine($"Compass - Magnetic Field Y: {args.Reading.MagneticField.Y}");
        Console.WriteLine($"Compass - Magnetic Field Z: {args.Reading.MagneticField.Z}");
    };
}

Gyroscopes

The Gyroscopes class allows you to access the device's gyroscope, which measures angular velocity.

using Microsoft.Maui.Devices.Sensors;

if (Gyroscopes.IsMonitoring)
{
    Gyroscopes.Stop();
}
else
{
    Gyroscopes.Start(SensorSpeed.UI);
    Gyroscopes.ReadingChanged += (sender, args) =>
    {
        Console.WriteLine($"Gyroscopes - Angular Velocity X: {args.Reading.AngularVelocity.X}");
        Console.WriteLine($"Gyroscopes - Angular Velocity Y: {args.Reading.AngularVelocity.Y}");
        Console.WriteLine($"Gyroscopes - Angular Velocity Z: {args.Reading.AngularVelocity.Z}");
    };
}

Magnetometer

The Magnetometer class allows you to access the device's magnetometer, which measures magnetic field strength.

using Microsoft.Maui.Devices.Sensors;

if (Magnetometer.IsMonitoring)
{
    Magnetometer.Stop();
}
else
{
    Magnetometer.Start(SensorSpeed.UI);
    Magnetometer.ReadingChanged += (sender, args) =>
    {
        Console.WriteLine($"Magnetometer - Magnetic Field X: {args.Reading.MagneticField.X}");
        Console.WriteLine($"Magnetometer - Magnetic Field Y: {args.Reading.MagneticField.Y}");
        Console.WriteLine($"Magnetometer - Magnetic Field Z: {args.Reading.MagneticField.Z}");
    };
}

Geolocation

The Geolocation class allows you to retrieve the device's current location. Note that this requires user permission.

using Microsoft.Maui.Devices.Sensors;

async Task GetLocationAsync()
{
    try
    {
        var location = await Geolocation.GetLastKnownLocationAsync();
        if (location == null)
        {
            location = await Geolocation.GetLocationAsync(new GeolocationRequest
            {
                DesiredAccuracy = GeolocationAccuracy.Medium,
                Timeout = TimeSpan.FromSeconds(30)
            });
        }

        if (location != null)
        {
            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
        }
    }
    catch (FeatureNotSupportedException fnsEx)
    {
        // Handle not supported on device
        Console.WriteLine($"Geolocation not supported: {fnsEx.Message}");
    }
    catch (PermissionException pEx)
    {
        // Handle permission denied
        Console.WriteLine($"Permission denied: {pEx.Message}");
    }
    catch (Exception ex)
    {
        // Unable to get location
        Console.WriteLine($"Unable to get location: {ex.Message}");
    }
}

await GetLocationAsync();
Haptics and Feedback >

Haptics and Feedback

Provide tactile feedback to the user using the device's vibration capabilities.

HapticFeedback

The HapticFeedback class allows you to trigger different types of haptic feedback.

using Microsoft.Maui.Devices;

// Trigger a light vibration
HapticFeedback.Perform(HapticFeedbackType.LightClick);

// Trigger a heavy vibration
// HapticFeedback.Perform(HapticFeedbackType.HeavyClick);
File Access >

File Access

Access application-specific directories for storing and retrieving files.

FileSystem

The FileSystem class provides methods to get paths to special directories.

using Microsoft.Maui.Storage;

// Get path to the app's cache directory
var cachePath = FileSystem.CacheDirectory;
Console.WriteLine($"Cache Directory: {cachePath}");

// Get path to the app's local app data directory
var localAppDataPath = FileSystem.AppDataDirectory;
Console.WriteLine($"App Data Directory: {localAppDataPath}");

// Example of writing to a file (requires more detailed implementation)
// var fileName = "mydata.txt";
// var filePath = Path.Combine(localAppDataPath, fileName);
// File.WriteAllText(filePath, "This is some data.");
Web Browsing >

Web Browsing

Open external web links in the device's default browser.

Browser

The Browser class provides a simple way to open URLs in an external browser.

using Microsoft.Maui.Essentials;

async Task OpenBrowserAsync(string url)
{
    try
    {
        await Browser.OpenAsync(url, BrowserLaunchMode.SystemPreferred);
    }
    catch (Exception ex)
    {
        // An unexpected error occurred
        Console.WriteLine($"Error opening browser: {ex.Message}");
    }
}

// Example usage:
// await OpenBrowserAsync("https://docs.microsoft.com/en-us/dotnet/maui/");