バッテリー情報の取得

このトピックでは、バッテリに関する詳細な情報 (バッテリーの充電、容量、バッテリーまたはバッテリーの集計の状態など) を含むバッテリ レポート を取得し、レポート内の項目に対する状態の変化を処理する方法について説明します。

コード例は、このトピックの最後に記載されている基本的なバッテリー アプリの例です。

バッテリーの集計レポートを取得する

一部のデバイスには複数のバッテリがあり、各バッテリがデバイスの全体的なエネルギー容量にどのように貢献するかは必ずしも明らかではありません。 ここで AggregateBattery クラスが登場します。 aggregate battery は、デバイスに接続されているすべてのバッテリ コントローラーを表し、BatteryReport オブジェクト全体を 1 つ提供できます。

Note

Battery クラスは、実際にはバッテリ コントローラーに対応します。 デバイスによっては、コントローラーが物理バッテリに取り付けられ、デバイス エンクロージャに取り付けられる場合があります。 したがって、バッテリが存在しない場合でも、バッテリ オブジェクトを作成できます。 それ以外の場合は、バッテリオブジェクトが nullされてもよい。

集計バッテリ オブジェクトを取得したら、GetReport を呼び出して、対応する 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);
}

個々のバッテリー レポートを取得する

また、個々のバッテリの BatteryReport オブジェクトを作成することもできます。 GetDeviceSelectorFindAllAsync メソッドを使用して、デバイスに接続されているすべてのバッテリ コントローラーを表す DeviceInformation オブジェクトのコレクションを取得します。 次に、目的の オブジェクトの Id プロパティを使用して、FromIdAsync メソッドを使用して対応する Battery を作成します。 最後に、 GetReport を呼び出して、個々のバッテリ レポートを取得します。

この例では、デバイスに接続されているすべてのバッテリのバッテリ レポートを作成する方法を示します。

private async Task RequestIndividualBatteryReports()
{
    // Find batteries.
    DeviceInformationCollection deviceInfo =
        await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
    foreach (DeviceInformation device in deviceInfo)
    {
        try
        {
            // Create battery object.
            Battery battery = await Battery.FromIdAsync(device.Id);

            // Get report.
            BatteryReport report = battery.GetReport();

            // Update UI.
            AddReportUI(BatteryReportPanel, report, battery.DeviceId);
        }
        catch { /* Add error handling, as applicable. */ }
    }
}

レポートの詳細にアクセスする

BatteryReport オブジェクトは、多くのバッテリ情報を提供します。 詳細については、そのプロパティに関する API リファレンスを参照してください。

この例では、このトピックの後半で説明する基本的なバッテリ アプリで使用されるバッテリ レポートのプロパティの一部を示します。

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() };

レポートの更新を要求する

Battery オブジェクトは、バッテリの充電、容量、または状態が変化したときに、ReportUpdated イベントをトリガーします。 これは通常、状態の変更の場合は直ちに発生し、その他のすべての変更に対して定期的に行われます。 この例では、バッテリ レポートの更新プログラムに登録する方法を示します。

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

レポートの更新を処理する

バッテリ更新が発生すると、ReportUpdated イベントは、対応する Battery オブジェクトをイベント ハンドラー メソッドに渡します。 ただし、このイベント ハンドラーは UI スレッドから呼び出されません。 この例に示すように、 DispatcherQueue オブジェクトを使用して UI の変更を呼び出す必要があります。

private async void AggregateBattery_ReportUpdated(Battery sender, object args)
{
    if (reportRequested)
    {
        DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, async () =>
        {
            await GetBatteryReport();
        });
    }
}

サンプル コード: 基本的なバッテリー アプリ

このサンプルでは、バッテリ API を使用して、アプリのユーザー インターフェイス (UI) にバッテリ情報を表示する方法を示します。 これには最小限の XAML UI が含まれていますが、メイン レポート UI は分離コードで作成されます。

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel x:Name="topPanel" Margin="24">
        <RadioButtons>
            <RadioButton x:Name="AggregateButton" Content="Aggregate results" IsChecked="True" />
            <RadioButton x:Name="IndividualButton" Content="Individual results"/>
        </RadioButtons>
        <Button Content="Get battery report" Click="GetReportButton_Click"  Margin="0,12,0,0"/>
    </StackPanel>

    <StackPanel x:Name="BatteryReportPanel" Grid.Row="1" Margin="24,0"/>
</Grid>
using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Windows.Devices.Enumeration;
using Windows.Devices.Power;

namespace DevicesDemo.Pages
{
    public sealed partial class BatteryInfoPage : Page
    {
        bool reportRequested = false;

        public BatteryInfoPage()
        {
            InitializeComponent();

            Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
        }

        private async void AggregateBattery_ReportUpdated(Battery sender, object args)
        {
            if (reportRequested)
            {
                DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, async () =>
                {
                    await GetBatteryReport();
                });
            }
        }

        private async void GetReportButton_Click(object sender, RoutedEventArgs e)
        {
            await GetBatteryReport();
        }

        private async Task GetBatteryReport()
        {
            // Clear UI.
            BatteryReportPanel.Children.Clear();

            if (AggregateButton.IsChecked == true)
            {
                // Request aggregate battery report.
                RequestAggregateBatteryReport();
            }
            else
            {
                // Request individual battery report.
                await RequestIndividualBatteryReports();
            }

            // Note request.
            reportRequested = true;
        }

        private void RequestAggregateBatteryReport()
        {
            // Create aggregate battery object.
            Battery aggBattery = Battery.AggregateBattery;

            // Get report.
            BatteryReport report = aggBattery.GetReport();

            // Update UI.
            AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
        }

        private async Task RequestIndividualBatteryReports()
        {
            // Find batteries.
            DeviceInformationCollection deviceInfo = 
                await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
            foreach (DeviceInformation device in deviceInfo)
            {
                try
                {
                    // Create battery object.
                    Battery battery = await Battery.FromIdAsync(device.Id);

                    // Get report.
                    BatteryReport 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);
        }
    }
}

Tip

BatteryReport オブジェクトから数値を受信するには、ローカル コンピューターまたは外部デバイスでアプリをデバッグします。 デバイス エミュレーターでデバッグする場合、BatteryReport オブジェクトは容量とレートのプロパティに null を返します。