Win10/UWP新特性系列—电池报告
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 大家可以进来一起学习~~
Win10/UWP新特性系列—电池报告的更多相关文章
- 【转】Win10/UWP新特性系列—Web
Internet Explorer Internet Explorer 在Windows 10 升级为Edge模式,是一种交互性和兼容性都很强的新型浏览器,该浏览器相比以前的版本更新了超过2000个操 ...
- Win10/UWP新特性系列—Launcher实现应用间的通信
UWP中,微软为Windows.System.Launcher启动器新增了很多的功能,以前只能启动App,打开指定扩展名文件,对uri协议的解析,以及当启动的应用没有安装时则会提示前往商店下载等. 如 ...
- Win10/UWP新特性系列—使用打印机
微软在Win10时代终于完成的设备系统的大统一,"56个民族,56支花……"(⊙o⊙)…,既然统一了,那么也就意味着API也统一了,所以在UWP中,我们就可以使用统一的打印API来 ...
- Win10/UWP新特性系列-GetPublisherCacheFolder
微软Windows Runtime App拥有很强的安全模型来防止不同App之间的数据获取和共享,也就是我们所说的"沙盒机制",每个App都运行在Windows沙盒中,App之间的 ...
- Win10/UWP新特性—Drag&Drop 拖出元素到其他App
在以前的文章中,写过微软新特性Drag&Drop,当时可能由于处于Win10预览版,使用的VS也是预览版,只实现了从桌面拖拽文件到UWP App中,没能实现从UWP拖拽元素到Desktop A ...
- Win10/UWP新特性—SharedStorageAccessManager 共享文件
首先先给大家推荐一个UWP/Win10开发者群:53078485 里面有很多大婶,还有很多学习资源,欢迎大家来一起讨论Win10开发! 在UWP开发中,微软提供了一个新的特性叫做SharedStor ...
- atitit。win7 win8 win9 win10 win11 新特性总结与战略规划
atitit.win7 win8 win9 win10 win11 新特性总结与战略规划 1. win7 1 1.1. 发布时间 2009年10月22日 1 1.2. 稳定性大幅提升,很少蓝屏死机 ...
- Java8新特性系列-默认方法
Java8 Interface Default and Static Methods 原文连接:Java8新特性系列-默认方法 – 微爱博客 在 Java 8 之前,接口只能有公共抽象方法. 如果不强 ...
- Java8新特性系列-Lambda
转载自:Java8新特性系列-Lambda – 微爱博客 Lambda Expressions in Java 8 Lambda 表达式是 Java 8 最流行的特性.它们将函数式编程概念引入 Jav ...
随机推荐
- selenium高亮显示操作步骤方法
package com.allin.pc;import java.util.List;import org.openqa.selenium.WebElement;import org.openqa.s ...
- iptables交互配置shell脚本
#!/bin/bash while true do clear echo "———————-menu————————" echo -e "\033[49;32;1m(1) ...
- [问题2014A05] 复旦高等代数 I(14级)每周一题(第七教学周)
[问题2014A05] (1) 设 \(x_1,x_2\cdots,x_n,x\) 都是未定元, \(s_k=x_1^k+x_2^k+\cdots+x_n^k\,(k\geq 1)\), \(s_0 ...
- struts的hello world小试
struts的hello world小试 前面jdk的安装和配置,tomcat的安装和配置以及java ide的安装和配置就不写了. 在项目中使用流程 创建一个Web项目 导如struts 2.0.1 ...
- iOS应用性能调优建议
本文来自iOS Tutorial Team 的 Marcelo Fabri,他是Movile的一名 iOS 程序员.这是他的个人网站:http://www.marcelofabri.com/,你还可以 ...
- KO Demo
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- 《K&R》中引用的几个排序算法(shellsort、)以及一个自己乱写的排序
留待期末考后更新... void shellsort(int v[], int n) { int gap, i, j, temp; ; gap > ; gap /= ) for(i = gap; ...
- IndexOutOfBoundsException ArrayList 访问越界
java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
- SSH2 框架下的分页
1.设计分页实体(pageBean) 这里我显示的是3-12页的方式: package cn.itcast.oa.domain; import java.util.List; /** * 封装分页信息 ...
- js中面向对象
1.对象的表示方法,以下是对象的两种方法:第二种方法是使用函数构造器来创建一个对象. 2.对象的一种表达方式,这种方式更像Java中对象的创建,就是用一个new来创建一个对象实例.面向对象的封装.样式 ...