由于项目需要,要求获取iOS手机电池电量的详细值以及变化量等信息。所以做了相关的技术调研,实现的方法有很多。所以写了这篇总结,对于当前获取电池电量的方式进行一个整理。
方法一:通过苹果给的api获取
最简单的方式
UIDevice currentDevice].batteryMonitoringEnabled = YES;
double deviceLevel = [UIDevice currentDevice].batteryLevel;
另外一种写法
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter]addObserverForName:UIDeviceBatteryLevelDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification*notification) {
NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel);
}];
测试多次会出现偏差1%左右,也就是说, 这个办法是存在缺陷的, 最起码, 它不精确。
方法二:通过runtime 获取StatusBar上电池电量控件类私有变量的值,此方法可精准获取iOS6以上电池电量
- (int)getCurrentBatteryLevel
{
UIApplication *app = [UIApplication sharedApplication];
if (app.