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 ...
随机推荐
- laravel框架总结(三) -- 路径分析
1.直接写绝对路径,这样会用在/goods/show前面加上域名 <a href="/goods/show?id=<?php echo $item['id']; ?>&qu ...
- void与void *
转载:http://blog.csdn.net/geekcome/article/details/6249151 void的含义 void即“无类型”,void *则为“无类型指针”,可以指向任何数据 ...
- android小知识之fragment中调用startActivityForResult(Intent intent,int requestcode)所遇到的问题
大家都知道对于Activity和Fragment都可以注册OnActivityResult()方法,但是要注意几点: a.当activity和fragment都注册了OnActivityResult( ...
- CentOS 7 最小化安装的网络配置
默认的最小化安装CentOS 7系统以后,是没有ipconfig这个命令的,依赖于net-tools工具包. 一.nmtui 这是一个类似于图形化的命令(和setup类似) 通过这个组件窗口可以设置各 ...
- 根据多年经验整理的《互联网MySQL开发规范》
一.基础规范 使用 INNODB 存储引擎 表字符集使用 UTF8 所有表都需要添加注释 单表数据量建议控制在 5000W 以内 不在数据库中存储图⽚.文件等大数据 禁止在线上做数据库压力测试 禁⽌ ...
- win7下的ipython没有的问题
在笔记本上安装python2.7后,执行python是可以的,但是ipython却不行. 一.问题排查 在网上搜索了看到python与ipython的区别: 例如:ipython有tab补全功能,然后 ...
- poj2778DNA Sequence(AC自动机+矩阵乘法)
链接 看此题前先看一下matrix67大神写的关于十个矩阵的题目中的一个,如下: 经典题目8 给定一个有向图,问从A点恰好走k步(允许重复经过边)到达B点的方案数mod p的值 把给定的图转为邻 ...
- centos 安装redis自启动要点
1.redis.conf a.daemonize yes b.pidfile /var/run/xxx.pid 2./etc/init.d/redis //加了下面三个注释部分,才支持设置开机自启动 ...
- django"动态网页","动态url","调试方法"
一.动态网页 其实只是每次刷新时,获取最新时间而已 1.urls.py from django.conf.urls import patterns, url, include urlpatterns ...
- telnet: connect to address xxxxxxx: No route to host
在要连接的服务上执行iptables -F