本主題說明如何取得包含詳細電池資訊(如電池或多電池集合的電量、容量與狀態)的 電池報告 ,並處理報告中任何項目的狀態變更。
程式碼範例來自本主題末尾列出的基本電池應用程式。
取得總電池報告
有些裝置有多個電池,且不一定清楚每個電池如何貢獻整體能量容量。 這正是 AggregateBattery 類別發揮作用的地方。 aggregate battery 代表所有連接到裝置的電池控制器,並可提供單一的整體 BatteryReport 物件。
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 物件。 使用 GetDeviceSelector搭配 FindAllAsync 方法,取得一組代表連接於裝置的電池控制器的 DeviceInformation物件集合。 接著,利用想要的 物件的 DeviceInformation 屬性,使用 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 介面,而主要的報告介面則是在程式碼後方建立的。
<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 的容量與速率屬性。