Let us see the procedure for creating a sample application that programmatically accesses the battery level in Windows Phone 8. Create a new project with a valid name. Once everything is ready our project looks as in the following screen.
![page name]()
Now add one Button control to the triggers and show the battery level, change the button name to “Battery Level”.
XAML Code
- <phone:PhoneApplicationPage
- x:Class="BatteryLevelDemo.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
- xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- FontFamily="{StaticResource PhoneFontFamilyNormal}"
- FontSize="{StaticResource PhoneFontSizeNormal}"
- Foreground="{StaticResource PhoneForegroundBrush}"
- SupportedOrientations="Portrait" Orientation="Portrait"
- shell:SystemTray.IsVisible="True">
- <Grid x:Name="LayoutRoot" Background="Transparent">
- <Grid.RowDefinitions>
- <RowDefinition Height="Auto"/>
- <RowDefinition Height="*"/>
- </Grid.RowDefinitions>
- <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
- <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
- <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
- </StackPanel>
- <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
- <Button x:Name="getbatteryLevel" Content="Battery Level" HorizontalAlignment="Left" Margin="168,153,0,0" VerticalAlignment="Top" Click="getbatteryLevel_Click"/>
- </Grid>
- </Grid>
- </phone:PhoneApplicationPage>
Now go to the code behind page. First we need to add the following reference for getting the battery level.
- using Windows.Phone.Devices.Power;
The Windows.Phone.Device.Power.Battery class can be used to retrieve the battery information in Windows Phone 8.
Now write the following code in the button click event.
C# Code
- private void getbatteryLevel_Click(object sender, RoutedEventArgs e)
- {
- string bateryLevel = Battery.GetDefault().RemainingChargePercent.ToString();
- MessageBox.Show(bateryLevel);
- }
The following is the sample code snippet to retrieve the battery level in Windows Phone 8.
![retrieve battery level]()
Use Battery.GetDefault().RemainingDischargeTime to get the discharge time .
Run the application by pressing the F5 Key and see the output as shown in the following.
![Run the application]()