Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Questo argomento descrive come ottenere un report sulla batteria che include informazioni dettagliate sulla batteria (ad esempio la carica, la capacità e lo stato di una batteria o un'aggregazione di batterie) e gestire le modifiche dello stato a tutti gli elementi del report.
Gli esempi di codice provengono dall'app a batteria di base elencata alla fine di questo argomento.
API Importanti
Scaricare un rapporto aggregato della batteria
Alcuni dispositivi hanno più di una batteria e non è sempre ovvio come ogni batteria contribuisce alla capacità energetica complessiva del dispositivo. È qui che entra in gioco la classe AggregateBattery. La batteria aggregata rappresenta tutti i controller della batteria connessi al dispositivo e può fornire un singolo oggetto BatteryReport.
Nota La Battery corrisponde effettivamente a un controller di batteria. A seconda del dispositivo, a volte il controller è collegato alla batteria fisica e a volte è collegato all'enclosure del dispositivo. Quindi, è possibile creare un oggetto batteria anche quando non sono presenti batterie. In altri casi, l'oggetto batteria può essere null.
Dopo aver creato un oggetto batteria aggregato, chiamare GetReport per ottenere il BatteryReport corrispondente.
private void RequestAggregateBatteryReport()
{
// Create aggregate battery object
var aggBattery = Battery.AggregateBattery;
// Get report
var report = aggBattery.GetReport();
// Update UI
AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
}
Ottenere rapporti individuali sulla batteria
È anche possibile creare un oggetto BatteryReport per ciascuna batteria. Usa
Questo esempio mostra come creare un report sulla batteria per tutte le batterie connesse 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 */ }
}
}
Accedi ai dettagli del report
L'oggetto BatteryReport fornisce molte informazioni sulla batteria. Per ulteriori informazioni, vedere il riferimento API per le sue proprietà: Status (un'enumerazione BatteryStatus), ChargeRateInMilliwatts, DesignCapacityInMilliwattHours, FullChargeCapacityInMilliwattHourse RemainingCapacityInMilliwattHours. Questo esempio mostra alcune delle proprietà del report della batteria usate dall'app della batteria di base, fornite più avanti in questo argomento.
...
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() };
...
...
Richiedere aggiornamenti dei report
L'oggetto Battery attiva l'evento ReportUpdated quando la carica, la capacità o lo stato della batteria cambia. Questo avviene in genere immediatamente per le modifiche di stato e periodicamente per tutte le altre modifiche. Questo esempio illustra come eseguire la registrazione per gli aggiornamenti del report della batteria.
...
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
...
Gestire gli aggiornamenti dei report
Quando si verifica un aggiornamento della batteria, l'evento ReportUpdated passa l'oggetto Battery corrispondente al metodo del gestore eventi. Tuttavia, questo gestore eventi non viene chiamato dal thread dell'interfaccia utente. È necessario usare l'oggetto Dispatcher per richiamare eventuali modifiche all'interfaccia utente, come illustrato in questo esempio.
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();
}
});
}
}
Esempio: app batteria semplice
Prova queste API creando una semplice app per la batteria in Microsoft Visual Studio. Nella pagina iniziale di Visual Studio, fai clic su Nuovo progetto, quindi sotto i modelli Visual C# > Windows > Universal, crea una nuova app usando il modello Blank App.
Aprire quindi il file MainPage.xaml e copiare il codice XML seguente in questo file (sostituendone il contenuto originale).
Annotazioni
Se l'app non è denominata App1, dovrai sostituire la prima parte del nome della classe nel frammento di codice seguente con lo spazio dei nomi dell'app. Ad esempio, se è stato creato un progetto denominato BasicBatteryApp, sostituire x:Class="App1.MainPage"
con x:Class="BasicBatteryApp.MainPage"
e xmlns:local="using:App1"
con 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>
Aprire quindi il file di MainPage.xaml.cs del progetto e sostituire il codice esistente con il codice seguente.
Annotazioni
Se l'app non è denominata App1, dovrai rinominare lo spazio dei nomi nell'esempio seguente con il nome assegnato al progetto. Ad esempio, se hai creato un progetto denominato BasicBatteryApp, sostituisci il namespace App1
con il namespace 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();
}
});
}
}
}
}
Suggerimento
Per ricevere valori numerici dall'oggetto BatteryReport, eseguire il debug dell'app nel computer locale o in un dispositivo esterno. Durante il debug in un emulatore di dispositivo, l'oggetto BatteryReport restituisce null alle proprietà di capacità e tasso.