How to get the Battery information in your Universal Windows Apps

How to get the Battery information in your Universal Windows Apps

If you are building an Universal Windows App, and want to check the status of the system battery, you can do it very easily.  It is also often helpful to notify your user with the battery status before your app perform any battery intensive operation or even showing a notification by asking plug-in charge when battery is low and no power supplied. The Windows.Devices.Power namespaces provides a set of API to deal with that.  In this post you will learn how to get battery reports and be notified of changes in your app.

Battery class provides information about a battery controller that is currently connected to  your device. It has a method called GetReport() that return a BatteryReport object that indicates the charge, capacity, and status of  the battery .

image

Getting the Battery Report

Step 1 : Include the required namespace

using Windows.System.Power

Step 2: Get the BatteryReport object by calling GetReport() method

var batteryReport = Battery.AggregateBattery.GetReport();

image

When the battery charged in full (100%) and it’s plugged in with power, the battery status would display as “Idel” as shown in above inspections.

image

Subsequently if you unplugged the power  cable, or charge your battery, you will find the exact status.

Status : Discharging

image

Status : Charging

image

BatteryReport class has additional property, such as DesignCapacityInMilliwattHours,FullChargeCapacityInMilliwattHours and RemainingCapacityInMilliwattHours which return rate of charging, full-charged energy capacity and reaming power capacity.  If there is no battery present, these values would be null.

Notify Battery Status

Step 1 : Subscribe the Event handler

ReportUpdated  event triggered automatically when there is any changes in charge, capacity, or status.  You can subscribed this event to notify  the user or application UI incase you need to update.

Battery.AggregateBattery.ReportUpdated += BatteryReportUpdated;

Step 2 : Then handle the BatteryReportUpdated event handler

private async void BatteryReportUpdated(Battery sender, object args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>;
{
var batteryReport = sender.AggregateBattery.GetReport();

…. // update UI elements

});
}

Hope this helps.

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

3 Comments to “How to get the Battery information in your Universal Windows Apps”

Comments are closed.