Share via


Detecting and Responding to Battery Status in UWP Apps

Introduction

Ever seen this icon? I bet you see it every single day probably or once in a couple of days. Yes.!! It's a sign of sadness and fear; this and no Wi-Fi. Users are now more fearful of this logo than anything else. When you see it, it's the moment when you do whatever you can to make sure that your device is up and running and does not die.

So whenever you see this, the normal thing you try to do is you plug in your beloved mobile device to the adapter. But you cannot do it every time. For example, when you are heading to somewhere. So what you will do? Take the heavy and unattractive charging pack with you, and attach your beautiful thin device with it? Right?

Well, this was never really a big issue before. But now, yes it is. Technology is growing rapidly and the rate of usage is greater than the rate of battery life or capacity. For example, you open a camera in your mobile device, which use the HD features, you take some snapshots, then apply filters on it, and then you may share it on social media. These all, of course will use your battery on every single moment. Sometimes intensive. See the chart below.

Being a developer, when we develop applications, we should also care about the User Experience (UX). When we talk about the User Experience, the first thing come to people's mind is `Design' of the application. But there are a lot other pieces that comes in User Experience. The one piece I am discussing about is reflected by the above low-battery icon. Developers sometimes don't often think that this is something they should care about. But keeping in mind the UX part of the application, one should do care about it.

Now I am going to show you an example about how you can make sure that the battery is charged the specific amount of percentage before using your application or the module of your application, if your application is battery intensive, e.g. use network, upload/download data, image manipulation etc. It's not a full fledge the application but it is definitely the part of the puzzle. It will show you that how you can help users with just few lines of code and ensure that you respect their device's battery life.

Configuration

So let's start. I will use a Custom Trigger that will create a very simple check on the amount of battery percentage. If it is below the specific or certain amount of percent, the application will ask the user to plug in the device before it do the battery intensive processing.

See the blow image, that's how our simple application will look like.

 

 

The design part is very simple, using the VisualStateManager and the Custom State Trigger will change the UI.

 

01.<Grid Background="Teal">
02.    <VisualStateManager.VisualStateGroups>
03.        <VisualStateGroup>
04.            <VisualState x:Name="PlentyOfBattery">
05.              ?  <VisualState.StateTriggers>
06.                    <local:BatteryTrigger Charging="False" />
07.                </VisualState.StateTriggers>
08.                <VisualState.Setters>
09.                    <Setter Target="StatusTextBlock.Text"
10.                            Value="Good to go!" />
11.                </VisualState.Setters>
12.            </VisualState>
13.            <VisualState x:Name="NeedsCharging">
14.                <VisualState.StateTriggers>
15.                    <local:BatteryTrigger Charging="True" />
16.                </VisualState.StateTriggers>
17.                <VisualState.Setters>
18.                    <Setter Target="StatusTextBlock.Text"
19.                            Value="Please plug in! Battery intensive process coming up" />
20.                </VisualState.Setters>
21.            </VisualState>
22.        </VisualStateGroup>
23.    </VisualStateManager.VisualStateGroups>
24.    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
25.        <TextBlock x:Name="BatteryPercentageTextBlock"
26.                    HorizontalAlignment="Center"
27.                    FontSize="64"
28.                    FontWeight="Normal" />
29.        <TextBlock x:Name="StatusTextBlock" FontSize="32" />
30.    </StackPanel>
31.</Grid>

Now we will create the BatteryTrigger.cs class, where all the magic will happen.

We have a built-in Battery class in Windows.Devices.Power namespace, from which we will get the aggregate (the sum of all batteries) battery power by AggregateBattery property. If you have more than one batteries, you can refer to the specific one by putting the battery ID. Now that I have the AggregateBattery property, I can get the report by GetReport() method which will tell the report of the battery whether the battery is fully charged, charging, discharging etc. And then I can update the status accordingly. See the below code.

 

1.public BatteryTrigger()
2.{
3.    Windows.Devices.Power.Battery.AggregateBattery.ReportUpdated 
4.        += async (sender, args) => await UpdateStatus();
5. 
6.    UpdateStatus();
7.}

Now the real magic remains to happen, here it is.

01.private async Task UpdateStatus()
02.{
03.    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
04.    {
05.        var batteryReport = Windows.Devices.Power.Battery.AggregateBattery.GetReport();
06.        var percentage = (batteryReport.RemainingCapacityInMilliwattHours.Value /
07.                            (double)batteryReport.FullChargeCapacityInMilliwattHours.Value);
08. 
09.        if (percentage < 0.40)
10.        {
11.            switch (batteryReport.Status)
12.            {
13.                case BatteryStatus.Charging:
14.                    SetActive(!this.Charging);
15.                    break;
16.                case BatteryStatus.Discharging:
17.                    SetActive(this.Charging);
18.                    break;
19.            }
20.        }
21.        else
22.        {
23.            SetActive(!this.Charging);
24.        }
25.    });
26.}

 

In this magical method, first I am getting the battery report using AggregateBattery property. Than using that report, I am calculating the current percentage of the battery by dividing the remaining capacity with full charge capacity (RemainingCapacityInMilliwattHours.Value / FullChargeCapacityInMilliwattHours.Value). Now I have the current percentage of the device's battery. I can now check to any specific amount of percentage. In this case, I am checking it with 40%, i.e. if battery is less than 40%, it shows the message to charge the battery. Otherwise it will display Good to go.

That's all for now. I am attaching the full source code of this application. Hope that helps.

Source Code

Battery.zip 

Reference

Original Article