Ottenere informazioni sulla batteria

Il presente argomento descrive come ottenere un report batteria che include informazioni dettagliate sulla batteria (ad esempio carica, capacità e stato di una batteria o aggregazione di batterie) e gestire le modifiche dello stato a qualsiasi elemento del report.

(BatteryReport)

Gli esempi di codice provengono dall'app di base per la batteria elencata alla fine di questo argomento.

API importanti

Ottenere un report sulla batteria aggregata

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 di batteria connessi al dispositivo e può fornire un singolo oggetto BatteryReport.

Nota Una classe Batteria corrisponde effettivamente a un controller della 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 potrebbe essere nullo.

Dopo aver creato un oggetto batteria aggregata, richiamare GetReport per ottenere il corrispondente BatteryReport.

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 report sulla batteria singola

È anche possibile creare un oggetto BatteryReport per singole batterie. Usare GetDeviceSelector con il metodo FindAllAsync per ottenere una raccolta di oggetti DeviceInformation che rappresentano tutti i controller della batteria connessi al dispositivo. Quindi, usando la proprietà Id dell'oggetto DeviceInformation desiderato, creare il corrispondente oggetto Battery con il metodo FromIdAsync. Infine, richiamare GetReport per ottenere il report della batteria singola.

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 */ }
    }
}

Dettagli del report di accesso

L'oggetto BatteryReport fornisce molte informazioni sulla batteria. Per altre info, vedi le informazioni di riferimento sulle API per le relative proprietà: Stato (un'enumerazione BatteryStatus ), ChargeRateInMilliwatts, DesignCapacityInMilliwattHours, FullChargeCapacityInMilliwattHours, e RemainingCapacityInMilliwattHours. Questo esempio mostra alcune tra le proprietà del report batteria usate dall'app di base per la batteria, 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 cambia la carica, la capacità o lo stato della batteria. In genere questo avviene 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 batteria.

...
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
...

Gestire gli aggiornamenti dei report

Quando si verifica un aggiornamento della batteria, l'evento ReportUpdated passa l'oggetto corrispondente Batteria al metodo del gestore eventi. Tuttavia, questo gestore eventi non viene richiamato 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 della batteria di base

Testare queste API creando la seguente app di base per la batteria in Microsoft Visual Studio. Dalla pagina iniziale di Visual Studio fare clic su Nuovo progetto, e poi utilizzando i modelli Visual C# > Windows > Universale, creare una nuova app con il modello App vuota.

Aprire quindi il file MainPage.xml e copiare il codice XML seguente in questo file (sostituendone il contenuto originale).

Nota

Se l'app non è denominata App1, sarà necessario 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>

Fatto questo, aprire il file di progetto MainPage.xaml.cs e sostituire il codice esistente con quello successivo.

Nota

Se l'app non è denominata App1, dovrai rinominare lo spazio dei nomi nell'esempio seguente con il nome assegnato al progetto. Ad esempio, se è stato creato un progetto denominato BasicBatteryApp, sostituire lo spazio dei nomi App1 con lo spazio dei nomi 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 su Computer locale o su un Dispositivo esterno. Durante il debug in un emulatore di dispositivo, l'oggetto BatteryReport restituisce il valore Nullo alle proprietà di capacità e frequenza.