2012-08-04 121 views
15

我使用这个函数来获取设备的当前电池电量:如何获取实时电池电量在iOS上有1%的粒度

[[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等值。

有没有解决方案来获得更高精度的百分比?

+0

所有细节,为了记录:我只是与iPhone 6 Plus进行检查你的代码,它并显示所有标水平,如0.49等 – brainray 2015-08-09 20:17:40

回答

10

看看这个网站: Reading the battery level programmatically

但是,要小心使用。所有这里使用的API在iPhone上都没有记录,如果你将这个应用程序提交给App Store,可能会导致拒绝。虽然电池充电状态不完全,但我建议使用UIDevice电池监控方法。

+0

感谢您的链接。我已经检查过它。我看到这一行:“不要忘记在发货前从代码中删除头文件和libIOKit.A.dylib!”,这是否意味着完成后,我可以删除libIOKit.A.dylib并从代码中移除头文件到上传到Apple Store? – cat 2012-08-06 01:51:55

2
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 
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; 
+1

你的第一行是多余的,因为你在第三行代码中完全一样。 – 2017-05-24 19:56:51

32

至少有四种不同的方法来读取电池电量,并且所有四种方式可能会返回不同的值。

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

值记录本的iOS项目:https://github.com/nst/BatteryChart

请查看代码以供参考。上述

iPhone 5 Battery

+0

此应用是否仍在运行并在后台报告百分比?或者你只是让应用程序运行? – simonthumper 2016-11-25 09:17:48

-1

这些问题的答案都非常好,但他们都在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; 
} 

我也有我的博客全文后给在here