Home > Developer Articles > Windows Phone SDK > How to retreive the Battery Level programatically in Windows Phone 8 ?

How to retreive the Battery Level programatically in Windows Phone 8 ?

One of the cool feature in Windows Phone 8 SDK is the inclusion of the Battery API in the SDK where the developers can use it to get the battery Level or the Remaining Charge in the WP8 device .

How to retreive the Battery Level programatically in Windows Phone 8 ?

To retreive the Battery Level of a Windows Phone 8 programatically , follow the below steps.

1. Include the name space Windows.Phone.Devices.Power in the codebehind file . This is because the Battery class is defined in the above namespace.

2. Retreive the Battery instance with the Battery.GetDefault()

3. Subscribe to the Battery.GetDefault().RemainingChargePercentChanged event handler where you could keep track of the battery remaining charge percent.

The Battery instance includes the property Battery.GetDefault().RemainingChargePercent which retreives the percentage of the charge remaining in the Windows Phone battery.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneApp3
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            // SK To display the Remaining Charge Percent
            Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercentChanged
+= MainPage_RemainingChargePercentChanged;
            MessageBox.Show(Windows.Phone.Devices.Power.Battery.GetDefault()
.RemainingChargePercent.ToString());

        }
        void MainPage_RemainingChargePercentChanged(object sender, object e)
        {
            MessageBox.Show(Windows.Phone.Devices.Power.Battery.GetDefault()
.RemainingChargePercent.ToString());
        }
    }
}
How to retreive the Battery Level programatically in Windows Phone 8 ?

How to retreive the Battery Level programatically in Windows Phone 8 ?

The following two tabs change content below.
Senthil Kumar is a Speaker , Blogger and Software Engineer from Bangalore. He is a Microsoft MVP in Client Development. He primarily works on .NET technologies like C# , ASP.NET MVC , Entity Framework , SQL Server etc. He is a Windows Phone Enthusiast and writes about Windows Phone and Mobile development at MobileOSGeek.com.

Leave a Reply