UWP中,新增了当节电模式开启时,App能获取到通知的API,通过响应电源条件的更改,比如咨询用户是否使用黑色背景等来帮助延长电池使用时间。
通过Windows.Devices.Power命名空间中的电池API,你可以了解到正在运行的设备所有的电池详细信息。
通过创建Battery对象来表示单个电池控制器或聚合的所有电池控制器,然后使用GetReport方法返回BatteryReport对象,该对象可指示响应电池的充电、容量和状态。
需要用到的资源:
- Battery:提供该设备的电池控制器信息类
- Battery.AggregateBattery:提供一个Battery的实例
- ReportUpdated:当电池控制器报告更新时的事件
- Battery. GetReport():获取电池报告对象BatteryReport
- BatteryReport:电池报告对象
- BatteryReport.Status:获取当前电池状态
- BatteryReport.ChargeRateInMilliwatts:充电速度
- BatteryReport.DesignCapacityInMilliwattHours:理论容量
- BatteryReport.FullChargeCapacityInMilliwattHours:冲满后的容量,总容量
- BatteryReport.RemainingCapacityInMilliwattHours:当前电量
下面写个Demo,来获取电池信息,以及处理电量低的时候的主题切换,(这里用充电中和没充电的状态来切换)
前台:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Center" Margin="6">
<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="GetBatteryReportButton_Click"
/>
</StackPanel>
<StackPanel x:Name="BatteryReportPanel" Margin="15,15,0,0"/>
</StackPanel>
</Grid>
后台:
public sealed partial class MainPage : Page
{
bool reportRequested;
public MainPage()
{
this.InitializeComponent();
//订阅电池状态更改事件
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
} private async void AggregateBattery_ReportUpdated(Battery sender, object args)
{
if (reportRequested)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//清空显示区UI元素
BatteryReportPanel.Children.Clear(); if (AggregateButton.IsChecked == true)
{
//多电池报告
RequestAggregateBatteryReport();
}
else
{
//单电池报告
RequestIndividualBatteryReports();
}
});
}
} /// <summary>
/// 获取 单个电池 报告
/// </summary>
private void RequestIndividualBatteryReports()
{
var aggBattery = Battery.AggregateBattery; var report = aggBattery.GetReport(); AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId);
} private void AddReportUI(StackPanel batteryReportPanel, BatteryReport report, string deviceId)
{
// 创建 电池报告 UI
var txt1 = new TextBlock { Text = "设备 ID: " + deviceId };
txt1.FontSize = ;
txt1.Margin = new Thickness(, , , );
txt1.TextWrapping = TextWrapping.WrapWholeWords; var txt2 = new TextBlock { Text = "电池状态: " + report.Status.ToString() };
ChangRequestedTheme(report.Status);
txt2.FontStyle = Windows.UI.Text.FontStyle.Italic;
txt2.Margin = new Thickness(, , , ); var txt3 = new TextBlock { Text = "充电速度 (mW): " + report.ChargeRateInMilliwatts.ToString() };
var txt4 = new TextBlock { Text = "理论产能 (mWh): " + report.DesignCapacityInMilliwattHours.ToString() };
var txt5 = new TextBlock { Text = "总容量 (mWh): " + report.FullChargeCapacityInMilliwattHours.ToString() };
var txt6 = new TextBlock { Text = "当前容量 (mWh): " + report.RemainingCapacityInMilliwattHours.ToString() }; // 创建电量比例UI
var pbLabel = new TextBlock { Text = "剩余电量百分比" };
pbLabel.Margin = new Thickness(, , , );
pbLabel.FontFamily = new FontFamily("Segoe UI");
pbLabel.FontSize = ; var pb = new ProgressBar();
pb.Margin = new Thickness(, , , );
pb.Width = ;
pb.Height = ;
pb.IsIndeterminate = false;
pb.HorizontalAlignment = HorizontalAlignment.Left; var pbPercent = new TextBlock();
pbPercent.Margin = new Thickness(, , , );
pbPercent.FontFamily = new FontFamily("Segoe UI");
pbLabel.FontSize = ; // 防止分母为0
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) * ).ToString("F2") + "%";
} // 添加页面元素
BatteryReportPanel.Children.Add(txt1);
BatteryReportPanel.Children.Add(txt2);
BatteryReportPanel.Children.Add(txt3);
BatteryReportPanel.Children.Add(txt4);
BatteryReportPanel.Children.Add(txt5);
BatteryReportPanel.Children.Add(txt6);
BatteryReportPanel.Children.Add(pbLabel);
BatteryReportPanel.Children.Add(pb);
BatteryReportPanel.Children.Add(pbPercent);
} /// <summary>
/// 根据电池使用状态改变Theme色
/// </summary>
/// <param name="status"></param>
private void ChangRequestedTheme(BatteryStatus status)
{
switch (status)
{
case BatteryStatus.NotPresent:
Debug.WriteLine(BatteryStatus.NotPresent.ToString());
break;
case BatteryStatus.Discharging:
//电池处于放电状态
Debug.WriteLine(BatteryStatus.Discharging.ToString());
//当电量百分比很低是可以采用 黑色主题
this.RequestedTheme = ElementTheme.Dark;
break;
case BatteryStatus.Idle:
Debug.WriteLine(BatteryStatus.Idle.ToString());
break;
case BatteryStatus.Charging:
//电池处于充电状态
Debug.WriteLine(BatteryStatus.Charging.ToString());
//正常模式
this.RequestedTheme = ElementTheme.Default;
break;
default:
break;
}
} /// <summary>
/// 获取 电池集 报告
/// </summary>
private async void RequestAggregateBatteryReport()
{
// 获取所有电池对象
var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());
foreach (DeviceInformation device in deviceInfo)
{
try
{
// 获取单个电池对象
var battery = await Battery.FromIdAsync(device.Id); // 获取电池报告
var report = battery.GetReport(); // 更新UI
AddReportUI(BatteryReportPanel, report, battery.DeviceId);
}
catch { /* Add error handling, as applicable */ }
}
} private void GetBatteryReportButton_Click(object sender, RoutedEventArgs e)
{
// 清除 UI
BatteryReportPanel.Children.Clear(); if (AggregateButton.IsChecked == true)
{
// 获取多电池报告
RequestAggregateBatteryReport();
}
else
{
// 获取单电池报告
RequestIndividualBatteryReports();
} reportRequested = true;
}
}
运行后我们可以看到,当电池状态处于放电时,界面会换成黑色主题来节约电池电量,当插上充电器时会换成默认的主题(我的默认是白色),实际开发中可根据电量百分比来决定是否切换节电主题来延长电池使用时间。
推荐一个UWP开发群:53078485 大家可以进来一起学习~~