Using .NET MAUI Essentials APIs Battery, Connectivity, Geolocation Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      17 mins read      Difficulty-Level: beginner

Using .NET MAUI Essentials APIs: Battery, Connectivity, Geolocation

.NET Multi-platform App UI (MAUI) Essentials provides a powerful set of APIs that simplify cross-platform app development. This includes functionalities such as Battery, Connectivity, and Geolocation, which are essential in many modern applications. This article dives into each of these APIs, detailing their usage and importance.

Battery API

The Battery API in .NET MAUI Essentials is crucial for applications that might need to operate on low battery or need to manage resources based on battery status. It allows developers to monitor battery level, power source, and charging state.

Key Methods and Properties:

  • Battery.ChargeLevel: Represents the battery charge level as a double value between 0.0 and 1.0. For example, a value of 0.5 indicates 50% battery.
  • Battery.State: Describes the power source (AC, Battery) and charging state (Charging, Discharging, Full).
  • Battery.EnergySaverStatus: Indicates if the device’s power-saving mode is enabled.
  • Battery.ChargeLevelChanged: Event that fires when the battery charge level changes.
  • Battery.StateChanged: Event that fires when the device’s power source changes.
  • Battery.EnergySaverStatusChanged: Event that fires when the phone's power-saving mode status changes.

Example Usage:

using Microsoft.Maui.Essentials;

public void MonitorBattery()
{
    // Subscribe to battery level changes
    Battery.ChargeLevelChanged += (s, e) =>
    {
        Console.WriteLine($"Battery level: {Battery.ChargeLevel * 100:F0}%");
    };

    // Subscribe to state changes
    Battery.StateChanged += (s, e) =>
    {
        Console.WriteLine($"Battery state: {Battery.State}");
    };

    // Subscribe to energy-saver mode changes
    Battery.EnergySaverStatusChanged += (s, e) =>
    {
        Console.WriteLine($"Energy-saver mode: {(Battery.EnergySaverStatus == BatteryEnergySaverStatus.On ? "On" : "Off")}");
    };
}

Connectivity API

The Connectivity API provides information about the network connection of the device. This is vital for applications that need to determine if the device has an internet connection and to act accordingly.

Key Methods and Properties:

  • Connectivity.ConnectionProfiles: Returns a list of active network connection profiles (e.g., Cellular, Wifi, Ethernet).
  • Connectivity.Changed: Event that fires when the user’s connectivity changes (e.g., when the device goes online or offline).

Example Usage:

using Microsoft.Maui.Essentials;

public void MonitorConnectivity()
{
    // Subscribe to connectivity changes
    Connectivity.ConnectivityChanged += (s, e) =>
    {
        var profiles = Connectivity.ConnectionProfiles;

        if (profiles.Contains(ConnectionProfile.Cellular))
            Console.WriteLine("Cellular connection available");
        else if (profiles.Contains(ConnectionProfile.WiFi))
            Console.WriteLine("WiFi connection available");
        else
            Console.WriteLine("No internet connection available");
    };
}

Geolocation API

The Geolocation API allows an application to retrieve the device’s current geographic location. This is essential for location-based services, including mapping, geofencing, and location-aware data retrieval.

Key Methods and Properties:

  • Geolocation.GetLastKnownLocationAsync(): Retrieves the last known location from the device. Can be faster as it avoids the need to request new location data.
  • Geolocation.GetLocationAsync(): Requests a new location from the device. This can take longer but guarantees up-to-date information.
  • Geolocation.RequestAccessAsync(): Requests location permissions from the user. This must be done before calling the methods above.
  • Location: Represents the geographical position of the device using the properties Latitude and Longitude.

Usage Example:

using Microsoft.Maui.Essentials;

public async Task GetCurrentLocation()
{
    try
    {
        var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();

        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
        }

        if (status == PermissionStatus.Granted)
        {
            var location = await Geolocation.GetLocationAsync();

            if (location != null)
            {
                Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
            }
        }
        else
        {
            Console.WriteLine("Permission to access location was denied.");
        }
    }
    catch (FeatureNotSupportedException fnsEx)
    {
        // Handle not supported on device exception
        Console.WriteLine(fnsEx);
    }
    catch (FeatureNotEnabledException fneEx)
    {
        // Handle not enabled on device exception
        Console.WriteLine(fneEx);
    }
    catch (PermissionException pEx)
    {
        // Handle permission exception
        Console.WriteLine(pEx);
    }
    catch (Exception ex)
    {
        // Handle other possible exceptions from the Geolocation API
        Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
    }
}

Conclusion

In summary, the Battery, Connectivity, and Geolocation APIs in .NET MAUI Essentials are powerful tools that enable developers to build feature-rich, cross-platform applications. These APIs allow for efficient resource management, dynamic network interaction, and location-based services, respectively. By leveraging these APIs, developers can create better user experiences while handling various real-world scenarios effectively.

Using .NET MAUI Essentials APIs: Battery, Connectivity, Geolocation

Introduction

.NET MAUI (Multi-platform App UI) Essentials is a collection of Xamarin-based libraries that provide easy access to cross-platform functionality such as battery status, network connectivity, geolocation, and more. In this guide, we will explore three of these capabilities: Battery, Connectivity, and Geolocation. We will walk through setting up a .NET MAUI application, integrating these APIs, and observing the data flow.

Step-by-Step Guide

Step 1: Set Up Your .NET MAUI Application

  1. Install .NET SDK and Visual Studio: Ensure you have the .NET 7 SDK and Visual Studio 2022 (Preview version for .NET MAUI) installed on your machine.
  2. Create a New Project:
    • Open Visual Studio.
    • Select "Create a new project."
    • Search for ".NET MAUI App" and select it.
    • Click "Next."
    • Configure your project by setting the project name, location, and solution name.
    • Click "Create."
  3. Check NuGet Package References:
    • Ensure that your project has the necessary NuGet packages for .NET MAUI Essentials.
    • Open YourProject.csproj and check if the following line is present:
    <PackageReference Include="Microsoft.Maui.Essentials" Version="7.0.101" />
    

Step 2: Add UI Elements for Battery Information

  1. Edit MainPage.xaml:

    • Open MainPage.xaml in your project.
    • Add UI elements to display battery information.
    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="MauiApp.MainPage">
    
        <StackLayout Padding="20">
            <Label Text="Battery Level" FontSize="16" />
            <Label x:Name="BatteryLevelLabel" FontSize="20" />
    
            <Label Text="Battery State" FontSize="16" />
            <Label x:Name="BatteryStateLabel" FontSize="20" />
    
            <Label Text="Battery Charge" FontSize="16" />
            <Label x:Name="BatteryChargeLabel" FontSize="20" />
        </StackLayout>
    </ContentPage>
    
  2. Code Behind MainPage.xaml.cs:

    • Open MainPage.xaml.cs.
    • Add logic to update battery information.
    using Microsoft.Maui.Essentials;
    using System;
    
    namespace MauiApp
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
                Battery.BatteryInfoChanged += Battery_BatteryInfoChanged;
                UpdateBatteryInfo();
            }
    
            private void UpdateBatteryInfo()
            {
                BatteryLevelLabel.Text = $"Charge: {Battery.ChargeLevel * 100:F0}%";
                BatteryStateLabel.Text = $"State: {Battery.State}";
                BatteryChargeLabel.Text = $"Charge Mode: {Battery.ChargeState}";
            }
    
            private void Battery_BatteryInfoChanged(object sender, BatteryInfoChangedEventArgs e)
            {
                UpdateBatteryInfo();
            }
    
            protected override void OnDisappearing()
            {
                base.OnDisappearing();
                Battery.BatteryInfoChanged -= Battery_BatteryInfoChanged;
            }
        }
    }
    

Step 3: Add UI Elements for Connectivity Information

  1. Edit MainPage.xaml:

    • Add UI elements to display connectivity information.
    <Label Text="Connectivity Profile" FontSize="16" />
    <Label x:Name="ConnectivityProfileLabel" FontSize="20" />
    
    <Label Text="Network Access" FontSize="16" />
    <Label x:Name="NetworkAccessLabel" FontSize="20" />
    
  2. Code Behind MainPage.xaml.cs:

    • Add logic to update connectivity information.
    using Microsoft.Maui.Essentials;
    using Microsoft.Maui.Controls;
    using System;
    
    namespace MauiApp
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
                Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
                UpdateConnectivityInfo();
            }
    
            private void UpdateConnectivityInfo()
            {
                var profiles = Connectivity.ConnectionProfiles;
                ConnectivityProfileLabel.Text = $"Profile: {string.Join(", ", profiles)}";
                NetworkAccessLabel.Text = $"Network Access: {Connectivity.NetworkAccess}";
            }
    
            private void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
            {
                UpdateConnectivityInfo();
            }
    
            protected override void OnDisappearing()
            {
                base.OnDisappearing();
                Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
            }
        }
    }
    

Step 4: Add UI Elements for Geolocation Information

  1. Edit MainPage.xaml:

    • Add UI elements to display geolocation information.
    <Label Text="Location" FontSize="16" />
    <Label x:Name="LocationLabel" FontSize="20" />
    
    <Button Text="Get Current Location" Clicked="GetLocationButton_Clicked" />
    
  2. Code Behind MainPage.xaml.cs:

    • Add logic to get and display geolocation information.
    using Microsoft.Maui.Essentials;
    using Microsoft.Maui.Controls;
    using System;
    
    namespace MauiApp
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            private async void GetLocationButton_Clicked(object sender, EventArgs e)
            {
                try
                {
                    var location = await Geolocation.GetLastKnownLocationAsync();
                    if (location == null)
                    {
                        var request = new GeolocationRequest(GeolocationAccuracy.Medium);
                        location = await Geolocation.GetLocationAsync(request);
                    }
    
                    if (location != null)
                    {
                        LocationLabel.Text = $"Latitude: {location.Latitude}, Longitude: {location.Longitude}";
                    }
                }
                catch (FeatureNotSupportedException fnsEx)
                {
                    await DisplayAlert("Not Supported", fnsEx.Message, "OK");
                }
                catch (FeatureNotEnabledException fneEx)
                {
                    await DisplayAlert("Not Enabled", fneEx.Message, "OK");
                }
                catch (PermissionException pEx)
                {
                    await DisplayAlert("Permission Denial", pEx.Message, "OK");
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Error", ex.Message, "OK");
                }
            }
        }
    }
    

Step 5: Run Your Application

  1. Set Your Platform:
    • In Visual Studio, select the platform you want to target (e.g., Android, iOS, Windows).
  2. Build and Run:
    • Click the "Run" button (or press F5) to build and run your application.
    • Observe how the battery, connectivity, and geolocation information is updated in real-time.

Understanding the Data Flow

  • Battery:

    • The Battery.BatteryInfoChanged event is triggered whenever the battery state or charge changes.
    • The Battery.ChargeLevel, Battery.State, and Battery.ChargeState properties provide information about the battery's current state.
    • We update the UI elements in response to this event.
  • Connectivity:

    • The Connectivity.ConnectivityChanged event is triggered whenever the network state changes.
    • The Connectivity.ConnectionProfiles and Connectivity.NetworkAccess properties provide information about the current network connectivity.
    • We update the UI elements in response to this event.
  • Geolocation:

    • The Geolocation.GetLastKnownLocationAsync method retrieves the last known location.
    • If no previous location is available, Geolocation.GetLocationAsync is called to request the current location.
    • Permissions must be granted for location access.
    • We display the latitude and longitude on the UI.

Conclusion

By following this step-by-step guide, you have created a .NET MAUI application that utilizes .NET MAUI Essentials APIs to monitor battery status, network connectivity, and geolocation. Understanding how these APIs work and how to integrate them into your application can greatly enhance its functionality and user experience. Experiment further with additional features provided by .NET MAUI Essentials to build more sophisticated applications.

Top 10 Questions and Answers on Using .NET MAUI Essentials APIs for Battery, Connectivity, and Geolocation

When developing applications with .NET Multi-platform App UI (MAUI), the .NET MAUI Essentials library provides a comprehensive set of cross-platform APIs to simplify common tasks such as accessing the device's battery state, checking network connectivity, and retrieving location data. Below are the top 10 questions and answers regarding these features.

1. How do I check the battery level of a device using .NET MAUI Essentials?

Answer: To check the battery level, you can use the Battery class from .NET MAUI Essentials. Here’s a simple snippet to get the battery level as a percentage:

using Microsoft.Maui.Essentials;

double chargeLevel = Battery.ChargeLevel; // chargeLevel is a value between 0.0 and 1.0

Additionally, you can subscribe to the Battery.BatteryInfoChanged event to detect changes in battery level, state, and source.

Battery.BatteryInfoChanged += OnBatteryInfoChanged;

void OnBatteryInfoChanged(object sender, BatteryInfoChangedEventArgs args)
{
    var level = args.ChargeLevel;
    var state = args.State; // BatteryState can be Charging, Full, Discharging, or NotCharging
    var source = args.Source; // BatteryPowerSource can be AC, Usb, Wireless, or Battery
}

2. How can I handle different types of network connectivity in a .NET MAUI application?

Answer: The Connectivity class from .NET MAUI Essentials allows you to monitor and react to network changes. You can check the current network access type and subscribe to changes.

using Microsoft.Maui.Essentials;

NetworkAccess networkAccess = Connectivity.Current.NetworkAccess; // NetworkAccess can be None, Local, ConstrainedInternet, or Internet

Connectivity.ConnectivityChanged += OnConnectivityChanged;

void OnConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
    var access = e.NetworkAccess; // access can be None, Local, ConstrainedInternet, or Internet
    var profiles = e.ConnectionProfiles; // profiles can be a list containing ConnectionProfile values like Unknown, Ethernet, Cellular, etc.
}

3. Can I request a high-accuracy location in a .NET MAUI app?

Answer: Yes, you can request location data with high accuracy using the Geolocation class. You can set the requested accuracy level and the timeout for the location request.

using Microsoft.Maui.Essentials;

try
{
    var request = new GeolocationRequest(GeolocationAccuracy.High, TimeSpan.FromSeconds(10));
    var location = await Geolocation.GetLocationAsync(request);

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

4. What permissions are needed to use Battery, Connectivity, and Geolocation features in .NET MAUI?

Answer: The required permissions vary depending on the platform:

  • Battery: No additional permissions are needed.
  • Connectivity: On Android, you need the ACCESS_NETWORK_STATE and ACCESS_WIFI_STATE permissions in your AndroidManifest.xml.
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    
  • Geolocation: On Android, you need both coarse (network-based) and fine (GPS-based) location permissions, as well as background location permission if required.
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    
    On iOS, add the following keys to your Info.plist:
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Allow access to location when the app is in use</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Allow access to location always</string>
    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Allow access to location always and when in use</string>
    

5. How can I check if the device supports GPS on .NET MAUI?

Answer: .NET MAUI Essentials itself does not provide a direct API to check GPS hardware availability, but you can use platform-specific APIs or check if specific permissions are granted.

using Microsoft.Maui.Essentials;
using Android.Locations;

public static bool IsGpsEnabled()
{
    if (DeviceInfo.Platform == DevicePlatform.Android)
    {
        LocationManager locationManager = (LocationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.LocationService);
        return locationManager.IsProviderEnabled(LocationManager.GpsProvider);
    }
    // For iOS, you would typically check the CLLocationManager status.
    return false;
}

6. How can I stop monitoring connectivity and battery changes in a .NET MAUI app?

Answer: To stop monitoring connectivity and battery changes, you can unsubscribe from the Connectivity.ConnectivityChanged and Battery.BatteryInfoChanged events.

Connectivity.ConnectivityChanged -= OnConnectivityChanged;
Battery.BatteryInfoChanged -= OnBatteryInfoChanged;

7. Is there a way to check the time remaining on the device’s battery when using .NET MAUI?

Answer: Unfortunately, the .NET MAUI Essentials Battery class does not provide direct access to the estimated time remaining on the battery. However, you can implement platform-specific solutions, such as using BatteryManager on Android.

using Android.Content;
using Android.OS;

public static int BatteryTimeRemaining()
{
    if (DeviceInfo.Platform == DevicePlatform.Android)
    {
        Intent batteryIntent = Android.App.Application.Context.RegisterReceiver(null, new IntentFilter(Intent.ActionBatteryChanged));
        int level = batteryIntent.GetIntExtra(BatteryManager.ExtraLevel, -1);
        int scale = batteryIntent.GetIntExtra(BatteryManager.ExtraScale, -1);
        int batteryPct = (int)((level / (float)scale) * 100.0f);

        int status = batteryIntent.GetIntExtra(BatteryManager.ExtraStatus, -1);
        bool isCharging = status == BatteryManager.BatteryStatusCharging || status == BatteryManager.BatteryStatusFull;

        if (isCharging)
            return -1; // Indicate charging

        // Assuming a flat drain rate, this is a very rough estimate
        // It's recommended to handle this using platform-specific API more accurately
        double drainRate = 5.0 / 60; // Example: 5% per hour
        double timeRemaining = (batteryPct / drainRate) * 60; // in minutes
        return (int)timeRemaining;
    }
    return -1; // Not supported
}

8. How can I use both Wi-Fi and cellular data together in my .NET MAUI app for connectivity?

Answer: By default, devices handle multiple network connections intelligently, using data only when necessary. To ensure your app can use both Wi-Fi and cellular data, ensure you have the necessary permissions and check if the network access is sufficient.

using Microsoft.Maui.Essentials;

NetworkAccess access = Connectivity.Current.NetworkAccess;

if (access == NetworkAccess.Internet)
{
    // Internet is available, proceed with network operations
}

In .NET MAUI, you do not have a direct way to specifically route traffic through Wi-Fi or cellular, but the OS will handle it based on your app's needs and the user's settings.

9. How can I request a one-time location fix using .NET MAUI Essentials?

Answer: To request a single location fix, you can use the Geolocation.GetLastKnownLocationAsync or Geolocation.GetLocationAsync methods. For a one-time request, GetLocationAsync is more appropriate.

using Microsoft.Maui.Essentials;

try
{
    var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(5));
    var location = await Geolocation.GetLocationAsync(request);

    if (location != null)
    {
        Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
    }
}
catch (Exception ex)
{
    // Handle the exception
}

10. Can I handle background location updates in a .NET MAUI application?

Answer: Handling background location updates can be platform-specific. On Android, you can use a ForegroundService to receive location updates even when the app is not in the foreground. On iOS, background location updates are handled differently and may require specific entitlements and configuration in Xcode. Here’s a simple example for starting a foreground service on Android using Xamarin.Essentials (compatible with .NET MAUI):

// Service code (Android)
[Service]
public class LocationService : Service
{
    public override IBinder OnBind(Intent intent) => null;

    public override int OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        LocationRequest request = new LocationRequest(2000) { SmallestDisplacement = 1 };
        FusedLocationProviderClient fusedLocationClient = LocationServices.GetFusedLocationProviderClient(this);
        fusedLocationClient.RequestLocationUpdates(request, new LocationCallback(this), Looper.MyLooper());
        return StartCommandResult.Sticky;
    }

    public override void OnDestroy()
    {
        FusedLocationProviderClient fusedLocationClient = LocationServices.GetFusedLocationProviderClient(this);
        fusedLocationClient.RemoveLocationUpdates(new LocationCallback(this));
        base.OnDestroy();
    }
}

// Location callback
public class LocationCallback : LocationCallback
{
    LocationService service;

    public LocationCallback(LocationService service)
    {
        this.service = service;
    }

    public override void OnLocationResult(LocationResult locationResult)
    {
        foreach (Android.Location.Location location in locationResult.Locations)
        {
            // Handle location update
            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}");
        }
    }
}

These questions and answers should provide a comprehensive guide to utilizing the Battery, Connectivity, and Geolocation APIs in .NET MAUI Essentials effectively.