Battery Class in Windows Phone 8 API

Introduction

With enhancement, Microsoft has also introduced a new class in the Windows Phone 8 SDK. One of the classes is the Battery class that allows developers to query Battery usage. It belongs to the Windows.Phone.Device.Power namespace.



Procedures

Step 1

Create a Windows Phone 8 project that has two simple text blocks.



Step 2

Next, we will try to put some code in the constructor. So that on every initiation of the page it will be invoked.

Or, you may use the onNavigatedTo() method instead of the constructor.

Ensure you have added a "using Windows.Phone.Devices.Power;" in your namespace.

  1. Battery myBattery; // reference  
  2.   
  3.  public MainPage()  
  4.  {  
  5.    InitializeComponent();  
  6.   
  7. percentRemaing.Text = Battery.GetDefault().RemainingChargePercent.ToString() + " %";  
  8.   
  9. timRemaing.Text = Battery.GetDefault().RemainingDischargeTime.TotalMinutes.ToString() + " minutes";  
  10.               
  11.   } 

Here, we have two named Text Blocks, percentRemaing and timRemaing.

Next, we have created an instance of the Battery class by Battery.GetDeafault() along with the property "RemaingChargePaercent".

The entire statement returns a string value that we have assigned to respective Text blocks.

Similarly, we have done in the Remaining discharge time.

Now, what will the output be like?



Note: Remaining Battery will always be 100% in case of the emulator. If you really want to experience some exact figures then try it in a real device.


Similar Articles