In .NET MAUI, you can check the device's battery level using the Battery class from the Microsoft.Maui.Devices namespace. Here's how to implement it:
Basic Implementation
First, add the necessary namespace to your file:
using Microsoft.Maui.Devices;
Get the battery level:
public double GetBatteryLevel() { // Returns a value between 0.0 and 1.0 return Battery.Default.ChargeLevel; }
Complete Example with UI
Here's a more complete example with a UI that displays the battery level:
using Microsoft.Maui.Controls; using Microsoft.Maui.Devices; namespace YourNamespace { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); CheckBattery(); // Optional: Subscribe to battery level changes Battery.Default.BatteryInfoChanged += Battery_BatteryInfoChanged; } private void CheckBattery() { var level = Battery.Default.ChargeLevel; BatteryLabel.Text = $"Battery Level: {level * 100}%"; // You can also check other properties: var state = Battery.Default.State; var powerSource = Battery.Default.PowerSource; } private void Battery_BatteryInfoChanged(object sender, BatteryInfoChangedEventArgs e) { // Update UI when battery level changes MainThread.BeginInvokeOnMainThread(() => { BatteryLabel.Text = $"Battery Level: {e.ChargeLevel * 100}%"; // You can also check: // e.State - Charging, Discharging, Full, NotCharging, Unknown // e.PowerSource - Battery, AC, Usb, Wireless, Unknown }); } } }
XAML for the Example
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="YourNamespace.MainPage"> <VerticalStackLayout> <Label x:Name="BatteryLabel" Text="Checking battery level..." HorizontalOptions="Center" VerticalOptions="Center" /> </VerticalStackLayout> </ContentPage>
Important Notes
Permissions: On Android, you need to add the
BATTERY_STATSpermission to yourPlatforms/Android/AndroidManifest.xml:
<uses-permission android:name="android.permission.BATTERY_STATS" />Platform Differences:
On iOS, you can only read the battery level (not write)
On Windows, this requires the "Power" capability
Battery State: You can also check:
Battery.Default.State(Charging, Discharging, Full, NotCharging, Unknown)Battery.Default.PowerSource(Battery, AC, Usb, Wireless, Unknown)
Energy Saver: You can also check if the device is in energy saver mode:
var energySaverStatus = Battery.Default.EnergySaverStatus;
No comments:
Post a Comment