Mobile Zone is brought to you in partnership with:

I’m a passionate software developer. I was born in Québec, Canada. I work at Mirego; a company specializing in mobile applications. I am the Windows Phone and Windows 8 specialist. My friends describe me as a Microsoft Evangelist. I love C# programming with Visual Studio, the .NET Framework, the Windows Phone and the Windows 8. When I’m not in front of a computer, my hobbies include playing bridge, poker and other card games, biking, reading technology news. Sébastien is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Windows Phone 8 Battery API

08.15.2012
| 5215 views |
  • submit to reddit

The Battery API makes a nice addition to the WP8 SDK.

I can see in the near future that some applications will display the battery metrics on a Live Tile or in the application that hides the System Tray.

The Battery API is pretty easy to use:
1- Get the Battery instance with Battery.GetDefault().
2- Bind to the event RemainingChargePercentChanged.

The battery properties are:
- RemainingChargePercent: gets a value that indicates the percentage of the charge remaining on the phone’s battery.
- RemainingDischargeTime: gets a value that estimates how much time is left until the phone’s battery is fully discharged. 

With the following code:

using Windows.Phone.Devices.Power;

namespace BatteryApp
{
    public partial class MainPage
    {
        private readonly Battery _battery;

        public MainPage()
        {
            InitializeComponent();

            _battery = Battery.GetDefault();

            _battery.RemainingChargePercentChanged += OnRemainingChargePercentChanged;

            UpdateUI();
        }

        private void OnRemainingChargePercentChanged(object sender, object e)
        {
            UpdateUI();
        }

        private void UpdateUI()
        {
            textBlockRemainingCharge.Text = string.Format("{0} %", _battery.RemainingChargePercent);
            textBlockDischargeTime.Text = string.Format("{0} minutes", _battery.RemainingDischargeTime.TotalMinutes);
        }
    }
}

 

You get:

image


Please note that when running this on the emulator, it will show 100% and an infinite discharge time. The above values are fake.

Get ready to code!

Published at DZone with permission of Sébastien Lachance, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)