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,来获取电池信息,以及处理电量低的时候的主题切换,(这里用充电中和没充电的状态来切换)
前台:?
1 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 2 <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 3 <StackPanel VerticalAlignment="Center" Margin="6"> 4 <RadioButton x:Name="AggregateButton" Content="Aggregate results" 5 GroupName="Type" IsChecked="True"/> 6 <RadioButton x:Name="IndividualButton" Content="Individual results" 7 GroupName="Type" IsChecked="False"/> 8 </StackPanel> 9 <StackPanel Orientation="Horizontal"> 10 <Button x:Name="GetBatteryReportButton" 11 Content="Get Battery Report" 12 Margin="15,15,0,0" Click="GetBatteryReportButton_Click" 13 /> 14 </StackPanel> 15 <StackPanel x:Name="BatteryReportPanel" Margin="15,15,0,0"/> 16 </StackPanel> 17 </Grid>
后台:
1 public sealed partial class MainPage : Page 2 { 3 bool reportRequested; 4 public MainPage() 5 { 6 this.InitializeComponent(); 7 //订阅电池状态更改事件 8 Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated; 9 } 10 11 private async void AggregateBattery_ReportUpdated(Battery sender, object args) 12 { 13 if (reportRequested) 14 { 15 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => 16 { 17 //清空显示区UI元素 18 BatteryReportPanel.Children.Clear(); 19 20 if (AggregateButton.IsChecked == true) 21 { 22 //多电池报告 23 RequestAggregateBatteryReport(); 24 } 25 else 26 { 27 //单电池报告 28 RequestIndividualBatteryReports(); 29 } 30 }); 31 } 32 } 33 34 /// <summary> 35 /// 获取 单个电池 报告 36 /// </summary> 37 private void RequestIndividualBatteryReports() 38 { 39 var aggBattery = Battery.AggregateBattery; 40 41 var report = aggBattery.GetReport(); 42 43 AddReportUI(BatteryReportPanel, report, aggBattery.DeviceId); 44 } 45 46 private void AddReportUI(StackPanel batteryReportPanel, BatteryReport report, string deviceId) 47 { 48 // 创建 电池报告 UI 49 var txt1 = new TextBlock { Text = "设备 ID: " + deviceId }; 50 txt1.FontSize = 15; 51 txt1.Margin = new Thickness(0, 15, 0, 0); 52 txt1.TextWrapping = TextWrapping.WrapWholeWords; 53 54 var txt2 = new TextBlock { Text = "电池状态: " + report.Status.ToString() }; 55 ChangRequestedTheme(report.Status); 56 txt2.FontStyle = Windows.UI.Text.FontStyle.Italic; 57 txt2.Margin = new Thickness(0, 0, 0, 15); 58 59 var txt3 = new TextBlock { Text = "充电速度 (mW): " + report.ChargeRateInMilliwatts.ToString() }; 60 var txt4 = new TextBlock { Text = "理论产能 (mWh): " + report.DesignCapacityInMilliwattHours.ToString() }; 61 var txt5 = new TextBlock { Text = "总容量 (mWh): " + report.FullChargeCapacityInMilliwattHours.ToString() }; 62 var txt6 = new TextBlock { Text = "当前容量 (mWh): " + report.RemainingCapacityInMilliwattHours.ToString() }; 63 64 // 创建电量比例UI 65 var pbLabel = new TextBlock { Text = "剩余电量百分比" }; 66 pbLabel.Margin = new Thickness(0, 10, 0, 5); 67 pbLabel.FontFamily = new FontFamily("Segoe UI"); 68 pbLabel.FontSize = 11; 69 70 var pb = new ProgressBar(); 71 pb.Margin = new Thickness(0, 5, 0, 0); 72 pb.Width = 200; 73 pb.Height = 10; 74 pb.IsIndeterminate = false; 75 pb.HorizontalAlignment = HorizontalAlignment.Left; 76 77 var pbPercent = new TextBlock(); 78 pbPercent.Margin = new Thickness(0, 5, 0, 10); 79 pbPercent.FontFamily = new FontFamily("Segoe UI"); 80 pbLabel.FontSize = 11; 81 82 // 防止分母为0 83 if ((report.FullChargeCapacityInMilliwattHours == null) || 84 (report.RemainingCapacityInMilliwattHours == null)) 85 { 86 pb.IsEnabled = false; 87 pbPercent.Text = "N/A"; 88 } 89 else 90 { 91 pb.IsEnabled = true; 92 pb.Maximum = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours); 93 pb.Value = Convert.ToDouble(report.RemainingCapacityInMilliwattHours); 94 pbPercent.Text = ((pb.Value / pb.Maximum) * 100).ToString("F2") + "%"; 95 } 96 97 // 添加页面元素 98 BatteryReportPanel.Children.Add(txt1); 99 BatteryReportPanel.Children.Add(txt2); 100 BatteryReportPanel.Children.Add(txt3); 101 BatteryReportPanel.Children.Add(txt4); 102 BatteryReportPanel.Children.Add(txt5); 103 BatteryReportPanel.Children.Add(txt6); 104 BatteryReportPanel.Children.Add(pbLabel); 105 BatteryReportPanel.Children.Add(pb); 106 BatteryReportPanel.Children.Add(pbPercent); 107 } 108 109 /// <summary> 110 /// 根据电池使用状态改变Theme色 111 /// </summary> 112 /// <param name="status"></param> 113 private void ChangRequestedTheme(BatteryStatus status) 114 { 115 switch (status) 116 { 117 case BatteryStatus.NotPresent: 118 Debug.WriteLine(BatteryStatus.NotPresent.ToString()); 119 break; 120 case BatteryStatus.Discharging: 121 //电池处于放电状态 122 Debug.WriteLine(BatteryStatus.Discharging.ToString()); 123 //当电量百分比很低是可以采用 黑色主题 124 this.RequestedTheme = ElementTheme.Dark; 125 break; 126 case BatteryStatus.Idle: 127 Debug.WriteLine(BatteryStatus.Idle.ToString()); 128 break; 129 case BatteryStatus.Charging: 130 //电池处于充电状态 131 Debug.WriteLine(BatteryStatus.Charging.ToString()); 132 //正常模式 133 this.RequestedTheme = ElementTheme.Default; 134 break; 135 default: 136 break; 137 } 138 } 139 140 141 142 /// <summary> 143 /// 获取 电池集 报告 144 /// </summary> 145 private async void RequestAggregateBatteryReport() 146 { 147 // 获取所有电池对象 148 var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector()); 149 foreach (DeviceInformation device in deviceInfo) 150 { 151 try 152 { 153 // 获取单个电池对象 154 var battery = await Battery.FromIdAsync(device.Id); 155 156 // 获取电池报告 157 var report = battery.GetReport(); 158 159 // 更新UI 160 AddReportUI(BatteryReportPanel, report, battery.DeviceId); 161 } 162 catch { /* Add error handling, as applicable */ } 163 } 164 } 165 166 private void GetBatteryReportButton_Click(object sender, RoutedEventArgs e) 167 { 168 // 清除 UI 169 BatteryReportPanel.Children.Clear(); 170 171 172 if (AggregateButton.IsChecked == true) 173 { 174 // 获取多电池报告 175 RequestAggregateBatteryReport(); 176 } 177 else 178 { 179 // 获取单电池报告 180 RequestIndividualBatteryReports(); 181 } 182 183 reportRequested = true; 184 } 185 }
运行后我们可以看到,当电池状态处于放电时,界面会换成黑色主题来节约电池电量,当插上充电器时会换成默认的主题(我的默认是白色),实际开发中可根据电量百分比来决定是否切换节电主题来延长电池使用时间。
推荐一个UWP开发群:53078485 大家可以进来一起学习~~
时间: 2024-10-08 12:26:47