次の方法で共有


バッテリー情報の取得

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

(BatteryReport)

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

重要な API

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

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

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

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

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

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

BatteryReport オブジェクトは、多くのバッテリ情報を提供します。 詳細については、プロパティの API リファレンスを参照してください。 Status ( BatteryStatus 列挙型)、 ChargeRateInMilliwattsDesignCapacityInMilliwattHoursFullChargeCapacityInMilliwattHours、および RemainingCapacityInMilliwattHours。 この例では、このトピックの後半で説明する、基本的なバッテリ アプリで使用されるバッテリ レポートのプロパティの一部を示します。

...
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 スレッドから呼び出されません。 この例に示すように、 Dispatcher オブジェクトを使用して UI の変更を呼び出す必要があります。

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

例: 基本的なバッテリー アプリ

Microsoft Visual Studio で次の基本的なバッテリー アプリをビルドして、これらの API をテストします。 Visual Studio のスタート ページで New Project をクリックし、Windows > Universal テンプレートの Visual C# >で、Blank App テンプレートを使用して新しいアプリを作成します。

次に、ファイル MainPage.xaml を開き、次の XML をこのファイルにコピーします (元の内容を置き換えます)。

Note

アプリの名前が App1 でない場合は、次のスニペットのクラス名の最初の部分をアプリの名前空間に置き換える必要があります。 たとえば、 BasicBatteryApp という名前のプロジェクトを作成した場合、 x:Class="App1.MainPage"x:Class="BasicBatteryApp.MainPage" に置き換え、 xmlns:local="using:App1"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>

次に、プロジェクトの MainPage.xaml.cs ファイルを開き、既存のコードを次のコードに置き換えます。

Note

アプリの名前が App1 でない場合は、次の例の名前空間の名前をプロジェクトに付けた名前で変更する必要があります。 たとえば、 BasicBatteryApp という名前のプロジェクトを作成した場合、名前空間 App1 を名前空間 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();
                    }
                });
            }
        }
    }
}

ヒント

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