I am going to show you how you can get the status if battery is charged, discharged and the specific amount of percentage. It will show you how you can help users with just few lines of code and ensure that you respect their device’s battery life. It is also useful to notify the battery status before your app perform any battery intensive operation performed by asking plug-in charge when battery is low and no power supplied.
Let’s start.
Create new Windows 10 project and design using the following XAML code,
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <Grid.RowDefinitions>
- <RowDefinition Height="*"></RowDefinition>
- <RowDefinition Height="*"></RowDefinition>
- </Grid.RowDefinitions>
- <TextBlock x:Name="batteryStatusbox" HorizontalAlignment="Center" Grid.Row="0" VerticalAlignment="Center"></TextBlock>
- <ProgressBar x:Name="statusinPer" HorizontalAlignment="Center" Height="40" Grid.Row="1" VerticalAlignment="Top" Width="360" SmallChange="0.1" />
- </Grid>
Now go to code behind page
The Windows.Devices.Power namespaces provides a set of API to deal with battery.
Battery class provides information about a battery controller that is currently connected or not in your device.
GetReport() method helps you to return a BatteryReport object that indicates the charge, capacity, and status of the battery.
Write the following code,
- public sealed partial class MainPage: Page
- {
- public MainPage()
- {
- this.InitializeComponent();
- Windows.Devices.Power.Battery.AggregateBattery.ReportUpdated += AggregateBatteryOnReportUpdated;
- }
- private async void AggregateBatteryOnReportUpdated(Windows.Devices.Power.Battery sender, object args)
- {
- await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
-
- var details = sender.GetReport();
- var getPercentage = (details.RemainingCapacityInMilliwattHours.Value / (double) details.FullChargeCapacityInMilliwattHours.Value);
- var getStatus = details.Status;
- string per = getPercentage.ToString("##%");
- statusinPer.Value = getPercentage;
- batteryStatusbox.Text = "Status: " + getStatus + "-Percentage :" + per;
- });
- }
- }
We get the battery capacity value in milliwat’s and we need to convert it to percentage so I am changing the value using the following code.
- string per = getPercentage.ToString("##%");
Subscribe the Event handler ReportUpdated event triggered automatically when there is any changes in charge, capacity, or status.
Now run the app and see the output look like the following screen.
When battery is not charged,
When battery is charging,