Platform APIs in .NET MAUI
This document provides an overview of the platform-specific APIs available in .NET MAUI, enabling you to access native device features and functionality. These APIs are essential for building rich, performant, and deeply integrated cross-platform applications.
What are Platform APIs?
.NET MAUI abstracts many native platform features through its handler architecture. This allows you to write code once and have it run across Android, iOS, macOS, and Windows. However, sometimes you need to access specific native capabilities that aren't directly exposed by the default MAUI controls or abstractions. This is where platform-specific APIs come in.
The .NET MAUI Essentials library provides a set of cross-platform APIs that access native device capabilities. In addition to Essentials, you can also directly access platform-specific APIs using .NET's conditional compilation features or by leveraging platform-specific projects within your MAUI solution.
Device Information
Accessing information about the device is crucial for tailoring your application's experience. .NET MAUI Essentials provides several APIs for this purpose.
Device Info
The DeviceInfo
class provides properties like:
Model
: The device model (e.g., "iPhone 14 Pro").Manufacturer
: The device manufacturer (e.g., "Apple").Platform
: The operating system platform (e.g., "iOS", "Android").Idiom
: The device idiom (e.g., "Phone", "Tablet", "Desktop").DeviceType
: The type of device (e.g., "Physical", "Virtual").VersionString
: The operating system version.
Example usage:
var deviceInfo = DeviceInfo.Current;
Console.WriteLine($"Model: {deviceInfo.Model}");
Console.WriteLine($"OS Version: {deviceInfo.VersionString}");
Console.WriteLine($"Platform: {deviceInfo.Platform}");
Console.WriteLine($"Idiom: {deviceInfo.Idiom}");
Battery
The Battery
class allows you to monitor battery charge level and status.
Battery.Current.EnergySaverStatus
: Indicates if energy saver mode is enabled.Battery.Current.BatteryState
: The current battery state (e.g., "Charging", "Discharging").Battery.Current.BatteryDischargeFactor
: The approximate percentage of battery charge remaining.
You can subscribe to battery change events:
Battery.Current.BatteryChanged += (sender, args) =>
{
Console.WriteLine($"Battery State: {args.BatteryState}");
Console.WriteLine($"Charge Level: {args.BatteryDischargeFactor * 100}%");
};
Battery level monitoring might have limitations on certain platforms due to power saving policies.
Clipboard
Access the system clipboard to copy and paste text.
Clipboard.Current.SetTextAsync(string text)
: Copies text to the clipboard.Clipboard.Current.GetTextAsync()
: Retrieves text from the clipboard.
Example:
await Clipboard.Current.SetTextAsync("Hello MAUI!");
string clipboardText = await Clipboard.Current.GetTextAsync();
Console.WriteLine($"Clipboard content: {clipboardText}");
Connectivity
Check the current network connectivity status.
Connectivity.Current.NetworkAccess
: The current network access state (e.g., "Internet", "Local", "None").Connectivity.Current.RemoveConnectivityChanged()
andConnectivity.Current.ConnectivityChanged
: For listening to network changes.
var current = Connectivity.Current.NetworkAccess;
if (current == NetworkAccess.Internet)
{
Console.WriteLine("Connected to the internet!");
}
Always check for internet connectivity before attempting to make network requests.
Geolocation
Retrieve the device's current location. Requires appropriate permissions.
Geolocation.GetLastKnownLocationAsync()
Geolocation.GetLocationAsync(GeolocationRequest request)
var location = await Geolocation.GetLastKnownLocationAsync();
if (location != null)
{
Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
}
Ensure you have requested and been granted the necessary location permissions from the user. This API may not be available on all platforms or devices.
Haptics
Provide tactile feedback to the user using device vibration.
HapticFeedback.Default.Perform(HapticFeedbackType type)
Example:
await HapticFeedback.Default.Perform(HapticFeedbackType.Click);
Orientation
Detect and respond to device orientation changes.
DisplayInfo.Current.CurrentOrientation
: The current screen orientation.DisplayInfo.Current.OrientationChanged
: Event for listening to orientation changes.
var currentOrientation = DisplayInfo.Current.CurrentOrientation;
Console.WriteLine($"Current Orientation: {currentOrientation}");
DisplayInfo.Current.OrientationChanged += (sender, args) =>
{
Console.WriteLine($"New Orientation: {args.Orientation}");
};
Permissions
Manage and check permissions for various device features (e.g., camera, location, storage).
Permissions.CheckStatusAsync<T>()
Permissions.RequestAsync<T>()
Example for Location:
var status = await Permissions.CheckStatusAsync<GeolocationPermission>();
if (status != PermissionStatus.Granted)
{
status = await Permissions.RequestAsync<GeolocationPermission>();
}
if (status == PermissionStatus.Granted)
{
// Proceed to get location
}
Power Management
Detect if the device is charging or on battery power.
PowerManager.Current.IsCharging
: Indicates if the device is currently charging.
if (PowerManager.Current.IsCharging)
{
Console.WriteLine("Device is charging.");
}
Secure Storage
Securely store small amounts of data, such as authentication tokens or user preferences.
SecureStorage.Default.SetAsync(string key, string value)
SecureStorage.Default.GetAsync(string key)
await SecureStorage.Default.SetAsync("auth_token", "your_super_secret_token");
var token = await SecureStorage.Default.GetAsync("auth_token");
SecureStorage uses platform-specific secure storage mechanisms (e.g., Keychain on iOS, Keystore on Android).
SMS
Send SMS messages. This API often prompts the user to confirm sending.
Sms.ComposeAsync(SmsMessage message)
var message = new SmsMessage
{
Body = "Hello from .NET MAUI!",
Recipients = new string[] { "123-456-7890" }
};
await Sms.ComposeAsync(message);
Storage
Access persistent storage for your application's data. For file system access, you might need to use platform-specific APIs or a library like Xamarin.Essentials' FileSystem
class.
The FileSystem
class (part of .NET MAUI Essentials) provides access to common application directories.
FileSystem.AppDataDirectory
FileSystem.CacheDirectory
FileSystem.PublicStorageDirectory
string documentsPath = FileSystem.AppDataDirectory;
string filePath = Path.Combine(documentsPath, "mydata.txt");
File.WriteAllText(filePath, "Some data to save.");
Vibration
Control device vibration for alerts or feedback. This is often synonymous with Haptics in modern devices.
Vibration.Default.Vibrate(TimeSpan duration)
Vibration.Default.Cancel()
Vibration.Default.Vibrate(TimeSpan.FromSeconds(1));
Accessing Platform-Specific APIs Directly
For scenarios not covered by .NET MAUI Essentials, you can access platform-specific APIs directly. This is typically done using conditional compilation directives.
Example: iOS Specific API
#if IOS
using UIKit;
public static class IosSpecificHelper
{
public static void ShowAlert(string message)
{
UIApplication.SharedApplication.InvokeOnMainThread(() =>
{
var alert = UIAlertController.Create("MAUI Alert", message, UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
});
}
}
#endif
Example: Android Specific API
#if ANDROID
using Android.Widget;
using Android.App;
public static class AndroidSpecificHelper
{
public static void ShowToast(string message)
{
// This requires access to the current Activity context.
// In a real app, you'd pass the context or access it appropriately.
// For demonstration, assume context is available.
var context = Application.Context; // Simplified access
Toast.MakeText(context, message, ToastLength.Short).Show();
}
}
#endif
You can then call these methods from your shared code:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
// Example of calling platform-specific code
#if IOS
IosSpecificHelper.ShowAlert("Welcome to iOS!");
#elif ANDROID
AndroidSpecificHelper.ShowToast("Welcome to Android!");
#endif
}
}
When directly accessing platform APIs, consider creating wrapper classes or helper methods to keep your UI code clean and maintainable.
Platform-Specific Projects
For more complex platform integrations or when you need to modify platform-specific project settings, you can directly work within the Platforms
folder of your .NET MAUI project.
Platforms/iOS
Platforms/Android
Platforms/MacCatalyst
Platforms/Tizen
Platforms/Windows
Each folder contains platform-specific project files and code. You can add native libraries or modify project configurations here.
By understanding and utilizing these platform APIs, you can unlock the full potential of .NET MAUI to create powerful, device-aware, and engaging cross-platform applications.