如何在iOS上实时获取电池电量并以1%为粒度显示?

18

我正在使用这个函数获取设备当前的电池电量:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
UIDevice *myDevice = [UIDevice currentDevice];

[myDevice setBatteryMonitoringEnabled:YES];
double batLeft = (float)[myDevice batteryLevel]; 
NSLog(@"%f",batLeft);

但是结果的粒度为5%。例如:当手机电池电量为88%时,仅记录0.85的值。batteryLevel仅以0.05的增量返回值。例如:0.85、0.9、0.95,而不会返回像0.82或0.83这样的值。

是否有任何解决方案可以获得更高精度的百分比?


1
记录一下:我刚刚用 iPhone 6 Plus 检查了你的代码,它确实显示了所有标量级别,如0.49等。 - brainray
7个回答

33

至少有四种不同的方法可以读取电池电量,而所有这四种方法可能返回不同的值。

以下是这些值随时间变化的图表。

这些值是使用此iOS项目记录的:https://github.com/nst/BatteryChart

请参考代码。

iPhone 5电池


1
这个应用程序会在后台保持运行并报告百分比吗?还是你只是让应用程序保持运行? - simonthumper

10

请查看这个网站: 编程读取电池电量

但是要小心使用。所有在此处使用的API都未经iPhone官方文件记录,如果您将此应用程序提交到App Store,可能会被拒绝。尽管电池充电状态不是完全可靠的,但我建议使用UIDevice电池监控方法。


谢谢你提供的链接。我已经查看了它。我看到这一行:“在发布之前不要忘记从代码中删除头文件和libIOKit.A.dylib!”,这是不是意味着完成后,我可以删除libIOKit.A.dylib并从我的代码中删除头文件以上传到苹果商店? - cat

4
UIDevice *myDevice = [UIDevice currentDevice];    
[myDevice setBatteryMonitoringEnabled:YES];

double batLeft = (float)[myDevice batteryLevel] * 100;
NSLog(@"%.f", batLeft);    

NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft];    
lblLevel.text = levelLabel;

2
你的第一行代码是多余的,因为你在第三行代码中做了完全相同的事情。 - Victor Engel
1
@VictorEngel 我刚刚编辑了一下,删除了重复的代码行。感谢你指出这个问题。 - PaulMest

3

Swift 版本获取电池电量:

UIDevice.current.isBatteryMonitoringEnabled = true
let batteryLevel = UIDevice.current.batteryLevel 

batteryLevel 返回给我 0、39;0、40 的值。


它对我不起作用?我需要执行其他配置吗?我得到了-1作为答案。 - Maninder Singh
你写了这段代码吗? UIDevice.current.isBatteryMonitoringEnabled = true如果你没有写,你会得到-1。 - maxwell
是的,我写了这行代码 "UIDevice.current.isBatteryMonitoringEnabled = true"。此外,我是一个新手iOS应用程序开发者。我正在从ViewController的viewDidLoad()方法中调用此代码。另外,我连接的是模拟器,而不是实际的手机。这会有什么影响吗? - Maninder Singh
1
当然,模拟器会返回“-1”。请仅在真实设备上使用此代码。 - maxwell

2

上面的答案都很好,但它们都是用Obj-C编写的。我已经将这些与其他示例一起在MonoTouch上执行了相同的任务,因此我在这里放置我的代码,以防有人需要:

try
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
    _Battery.Level = (int)(UIDevice.CurrentDevice.BatteryLevel * IOSBatteryLevelScalingFactor);
    _Battery.State = UIDevice.CurrentDevice.BatteryState;
}
catch (Exception e)
{
    ExceptionHandler.HandleException(e, "BatteryState.Update");
    throw new BatteryUpdateException();
}
finally
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;
}

我在博客上写了一篇完整的文章,在这里可以找到所有细节。


1

你可以在这里找到一个完美的答案

Xcode: 11.4 Swift: 5.2

点击这里


0
如果您正在使用Swift 5.1或更高版本,此代码肯定适用于您。
步骤1:首先启用当前设备的isBatteryMonitoringEnabled属性,如下所示,以开始操作:
UIDevice.current.isBatteryMonitoringEnabled = true

步骤2:- 您现在可以读取当前电池电量

let level = UIDevice.current.batteryLevel
print(level)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接