Obtener información sobre la batería
En este tema se describe cómo obtener un informe de batería que incluye información detallada de la batería (como la carga, la capacidad y el estado de una batería o un agregado de baterías) y controlar los cambios de estado en los elementos del informe.
Los ejemplos de código provienen de la aplicación de batería básica que aparece al final de este tema.
API importantes
Obtener un informe de un conjunto de baterías
Algunos dispositivos tienen más de una batería y no siempre resulta obvio saber cómo contribuye cada una de ellas a la capacidad de energía global del dispositivo. Aquí es donde entra en acción la clase AggregateBattery. El agregado de baterías representa todos los controladores de la batería conectados al dispositivo y puede proporcionar un único objeto BatteryReport general.
Nota Una clase Battery corresponde realmente a un controlador de batería. Según el dispositivo, unas veces se adjunta el controlador a la batería física y otras a la carcasa del dispositivo. Por tanto, es posible crear un objeto de batería, incluso cuando no hay baterías presentes. Otras veces, el objeto de batería puede ser null.
Una vez tengas un objeto del agregado de batería, llama a GetReport para obtener la clase BatteryReport correspondiente.
private void RequestAggregateBatteryReport()
{
// Create aggregate battery object
var aggBattery = Battery.AggregateBattery;
// Get report
var report = aggBattery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
}
Obtener informes de batería individuales
También puedes crear un objeto BatteryReport para baterías individuales. Usa GetDeviceSelector con el método FindAllAsync para obtener una colección de objetos DeviceInformation que representen los controladores de la batería que están conectados al dispositivo. A continuación, mediante la propiedad Id del objeto DeviceInformation que quieras usar, crea la clase Battery correspondiente con el método FromIdAsyn. Por último, llama a GetReport para obtener el informe de batería.
Este ejemplo muestra cómo crear un informe de batería para todas las baterías conectadas al dispositivo.
async private void RequestIndividualBatteryReports()
{
// Find batteries
var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
foreach(DeviceInformation device in deviceInfo)
{
try
{
// Create battery object
var battery = await Battery.FromIdAsync(device.Id);
// Get report
var report = battery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, battery.DeviceId);
}
catch { /* Add error handling, as applicable */ }
}
}
Detalles del informe de acceso
El objeto BatteryReport proporciona mucha información sobre la batería. Para obtener más información, consulta la referencia de la API acerca de sus propiedades: Status (una enumeración BatteryStatus), ChargeRateInMilliwatts, DesignCapacityInMilliwattHours, FullChargeCapacityInMilliwattHours y RemainingCapacityInMilliwattHours. Este ejemplo muestra algunas de las propiedades del informe de batería que usa la aplicación de batería básica, la cual se proporciona más adelante en este tema.
...
TextBlock txt3 = new TextBlock { Text = "Charge rate (mW): " + report.ChargeRateInMilliwatts.ToString() };
TextBlock txt4 = new TextBlock { Text = "Design energy capacity (mWh): " + report.DesignCapacityInMilliwattHours.ToString() };
TextBlock txt5 = new TextBlock { Text = "Fully-charged energy capacity (mWh): " + report.FullChargeCapacityInMilliwattHours.ToString() };
TextBlock txt6 = new TextBlock { Text = "Remaining energy capacity (mWh): " + report.RemainingCapacityInMilliwattHours.ToString() };
...
...
Solicitar actualizaciones de informe
El objeto Battery desencadena el evento ReportUpdated cuando cambia el estado de la batería, la capacidad o la carga. Generalmente esto sucede de forma inmediata para los cambios de estado y periódicamente para los demás cambios. Este ejemplo muestra cómo registrarse para recibir las actualizaciones del informe de batería.
...
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
...
Controlar las actualizaciones del informe
Cuando se produce una actualización de la batería, el evento ReportUpdated pasa el correspondiente objeto Battery al método del controlador de eventos. Sin embargo, no se llama al controlador de eventos desde el subproceso de la interfaz de usuario. Tendrás que usar el objeto Dispatcher para invocar cualquier cambio en la interfaz de usuario, tal y como se muestra en este ejemplo.
async private void AggregateBattery_ReportUpdated(Battery sender, object args)
{
if (reportRequested)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Clear UI
BatteryReportPanel.Children.Clear();
if (AggregateButton.IsChecked == true)
{
// Request aggregate battery report
RequestAggregateBatteryReport();
}
else
{
// Request individual battery report
RequestIndividualBatteryReports();
}
});
}
}
Ejemplo: aplicación de batería básica
Prueba estas API mediante la creación de la siguiente aplicación de batería básica en Microsoft Visual Studio. En la página de inicio de Visual Studio, haz clic en Nuevo proyecto y, a continuación, en las plantillas Visual C# > Windows > Universal; crea una nueva aplicación usando la plantilla Aplicación vacía.
Después abre el archivo MainPage.xaml y copia el siguiente XML en el archivo (y reemplaza su contenido original).
Nota
Si la aplicación no se denomina App1, deberá reemplazar la primera parte del nombre de clase en el siguiente fragmento de código por el espacio de nombres de la aplicación. Por ejemplo, si ha creado un proyecto denominado BasicBatteryApp, reemplace por x:Class="App1.MainPage"
x:Class="BasicBatteryApp.MainPage"
y xmlns:local="using:App1"
por xmlns:local="using:BasicBatteryApp"
.
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" >
<StackPanel VerticalAlignment="Center" Margin="15,30,0,0" >
<RadioButton x:Name="AggregateButton" Content="Aggregate results" GroupName="Type" IsChecked="True" />
<RadioButton x:Name="IndividualButton" Content="Individual results" GroupName="Type" IsChecked="False" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="GetBatteryReportButton"
Content="Get battery report"
Margin="15,15,0,0"
Click="GetBatteryReport"/>
</StackPanel>
<StackPanel x:Name="BatteryReportPanel" Margin="15,15,0,0"/>
</StackPanel>
</Page>
A continuación, abre el archivo MainPage.xaml.cs del proyecto y reemplaza el código existente por el siguiente.
Nota
Si la aplicación no se denomina App1, deberá cambiar el nombre del espacio de nombres en el ejemplo siguiente con el nombre que asignó al proyecto. Por ejemplo, si creaste un proyecto denominado BasicBatteryApp, reemplazarías el espacio de nombres App1
por BasicBatteryApp
.
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.Devices.Enumeration;
using Windows.Devices.Power;
using Windows.UI.Core;
namespace App1
{
public sealed partial class MainPage : Page
{
bool reportRequested = false;
public MainPage()
{
this.InitializeComponent();
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
}
private void GetBatteryReport(object sender, RoutedEventArgs e)
{
// Clear UI
BatteryReportPanel.Children.Clear();
if (AggregateButton.IsChecked == true)
{
// Request aggregate battery report
RequestAggregateBatteryReport();
}
else
{
// Request individual battery report
RequestIndividualBatteryReports();
}
// Note request
reportRequested = true;
}
private void RequestAggregateBatteryReport()
{
// Create aggregate battery object
var aggBattery = Battery.AggregateBattery;
// Get report
var report = aggBattery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
}
async private void RequestIndividualBatteryReports()
{
// Find batteries
var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
foreach(DeviceInformation device in deviceInfo)
{
try
{
// Create battery object
var battery = await Battery.FromIdAsync(device.Id);
// Get report
var report = battery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, battery.DeviceId);
}
catch { /* Add error handling, as applicable */ }
}
}
private void AddReportUI(StackPanel sp, BatteryReport report, string DeviceID)
{
// Create battery report UI
TextBlock txt1 = new TextBlock { Text = "Device ID: " + DeviceID };
txt1.FontSize = 15;
txt1.Margin = new Thickness(0, 15, 0, 0);
txt1.TextWrapping = TextWrapping.WrapWholeWords;
TextBlock txt2 = new TextBlock { Text = "Battery status: " + report.Status.ToString() };
txt2.FontStyle = Windows.UI.Text.FontStyle.Italic;
txt2.Margin = new Thickness(0, 0, 0, 15);
TextBlock txt3 = new TextBlock { Text = "Charge rate (mW): " + report.ChargeRateInMilliwatts.ToString() };
TextBlock txt4 = new TextBlock { Text = "Design energy capacity (mWh): " + report.DesignCapacityInMilliwattHours.ToString() };
TextBlock txt5 = new TextBlock { Text = "Fully-charged energy capacity (mWh): " + report.FullChargeCapacityInMilliwattHours.ToString() };
TextBlock txt6 = new TextBlock { Text = "Remaining energy capacity (mWh): " + report.RemainingCapacityInMilliwattHours.ToString() };
// Create energy capacity progress bar & labels
TextBlock pbLabel = new TextBlock { Text = "Percent remaining energy capacity" };
pbLabel.Margin = new Thickness(0,10, 0, 5);
pbLabel.FontFamily = new FontFamily("Segoe UI");
pbLabel.FontSize = 11;
ProgressBar pb = new ProgressBar();
pb.Margin = new Thickness(0, 5, 0, 0);
pb.Width = 200;
pb.Height = 10;
pb.IsIndeterminate = false;
pb.HorizontalAlignment = HorizontalAlignment.Left;
TextBlock pbPercent = new TextBlock();
pbPercent.Margin = new Thickness(0, 5, 0, 10);
pbPercent.FontFamily = new FontFamily("Segoe UI");
pbLabel.FontSize = 11;
// Disable progress bar if values are null
if ((report.FullChargeCapacityInMilliwattHours == null)||
(report.RemainingCapacityInMilliwattHours == null))
{
pb.IsEnabled = false;
pbPercent.Text = "N/A";
}
else
{
pb.IsEnabled = true;
pb.Maximum = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);
pb.Value = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);
pbPercent.Text = ((pb.Value / pb.Maximum) * 100).ToString("F2") + "%";
}
// Add controls to stackpanel
sp.Children.Add(txt1);
sp.Children.Add(txt2);
sp.Children.Add(txt3);
sp.Children.Add(txt4);
sp.Children.Add(txt5);
sp.Children.Add(txt6);
sp.Children.Add(pbLabel);
sp.Children.Add(pb);
sp.Children.Add(pbPercent);
}
async private void AggregateBattery_ReportUpdated(Battery sender, object args)
{
if (reportRequested)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Clear UI
BatteryReportPanel.Children.Clear();
if (AggregateButton.IsChecked == true)
{
// Request aggregate battery report
RequestAggregateBatteryReport();
}
else
{
// Request individual battery report
RequestIndividualBatteryReports();
}
});
}
}
}
}
Sugerencia
Para recibir valores numéricos del objeto BatteryReport , depure la aplicación en el equipo local o en un dispositivo externo. Al depurar en un emulador de dispositivo, el objeto BatteryReport devuelve null a las propiedades de capacidad y velocidad.
Comentarios
https://aka.ms/ContentUserFeedback.
Próximamente: A lo largo de 2024 iremos eliminando gradualmente GitHub Issues como mecanismo de comentarios sobre el contenido y lo sustituiremos por un nuevo sistema de comentarios. Para más información, vea:Enviar y ver comentarios de