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 ?

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you’ll learn about the Win32 Error “0x000019E5 – ERROR_COULD_NOT_RESIZE_LOG” that you get when debugging system erors in...
In this post, you’ll learn about the error “CO_E_DBERROR 0x8004E02B” that is returned when working with COM based APIs or...
In this post, you’ll learn about the Win32 Error “0x000019D0 – ERROR_LOG_BLOCK_VERSION” that you get when debugging system erors in...