다음을 통해 공유


배터리 정보 가져오기

이 항목은 자세한 배터리 정보(배터리 충전량, 용량, 배터리 또는 배터리 집계 상태 등)가 포함된 배터리 보고서를 가져오고 보고서의 모든 항목에 대한 상태 변경을 처리하는 방법에 대해 설명합니다.

(BatteryReport)

코드 예시는 이 항목의 끝에 나열된 기본 배터리 앱에서 제공됩니다.

중요 API

집계 배터리 보고서 가져오기

일부 디바이스에는 둘 이상의 배터리가 있으며 각 배터리가 디바이스의 전체 에너지 용량에 어떻게 기여하는지 항상 명확하지는 않습니다. AggregateBattery 클래스가 들어오는 위치입니다. 집계 배터리는 디바이스에 연결된 모든 배터리 컨트롤러를 나타내며 전체 BatteryReport 개체를 하나 제공할 수 있습니다.

참고 배터리 클래스는 실제로 배터리 컨트롤러에 해당합니다. 디바이스에 따라 컨트롤러가 물리적 배터리에 연결되고 때로는 디바이스 인클로저에 연결되어 있는 경우가 있습니다. 따라서 배터리가 없는 경우에도 배터리 개체를 만들 수 있습니다. 다른 경우에는 배터리 개체가 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 개체 컬렉션을 가져옵니다. 그런 다음 원하는 DeviceInformation 개체의 Id 속성을 사용하여 FromIdAsync 메서드로 해당 배터리를 만듭니다. 마지막으로 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 열거형), ChargeRateInMilliwatts, DesignCapacityInMilliwattHours, FullChargeCapacityInMilliwattHoursRemainingCapacityInMilliwattHours. 이 예시는 이 항목의 뒷부분에서 제공하는 기본 배터리 앱에서 사용하는 일부 배터리 보고서 속성을 보여줍니다.

...
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 시작 페이지에서 새 프로젝트를 클릭한 다음, Visual C# > Windows > Universal 템플릿 아래에서 빈 앱 템플릿을 사용하여 새 앱을 만듭니다.

그런 다음 MainPage.xaml 파일을 열고 다음의 XML을 이 파일에 복사합니다(원래 내용 바꾸기).

참고

앱 이름이 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 파일을 열고 기존 코드를 다음으로 바꿉니다.

참고

앱 이름이 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 개체에서 숫자 값을 받으려면 로컬 컴퓨터 또는 외부 디바이스에서 앱을 디버그합니다. 디바이스 Emulator에서 디버깅할 때 BatteryReport 개체는 용량 및 속도 속성에 null을 반환합니다.