iOS 获取电池电量技术调研总结

最近由于项目需要,要求获取iOS手机电池电量的详细值以及变化量等信息。所以做了相关的技术调研,调研到的方法有很多。各种网站给的代码和方法,有的东拼西凑,导致我走了很多弯路,所以写了这篇总结以供有相同需求的同学共同学习,并提高效率,如有不正确的地方,请多多指教。

方法一:通过苹果官方文档里面UIDevice public API来获取,代码如下:

[UIDevicecurrentDevice].batteryMonitoringEnabled =YES;  [[NSNotificationCenterdefaultCenter]addObserverForName:UIDeviceBatteryLevelDidChangeNotificationobject:nilqueue:[NSOperationQueuemainQueue] usingBlock:^(NSNotification*notification) {// Level has changed

NSLog(@"Battery Level Change");

NSLog(@"电池电量:%.2f", [UIDevicecurrentDevice].batteryLevel);

}];

// @property(nonatomic,readonly)float batteryLevel NS_AVAILABLE_IOS(3_0);

// 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown它返回的是0.00-1.00之间的浮点值。

但是经过测试发现,在iOS7 上 它是以0.05为单位的,但是在iOS9下测试,它是以0.01为单位的,虽然也是0.01为单位,但是测试多次也会出现偏差1%左右。也就是说, 这个办法是存在缺陷的, 最起码, 它不精确。

方法二:通过runtime 获取StatusBar上电池电量控件类私有变量的值,此方法可精准获取iOS6以上电池电量

MRC:

- (int)getCurrentBatteryLevel{

if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive|| [UIApplicationsharedApplication].applicationState==UIApplicationStateInactive) {

void *result = nil;

object_getInstanceVariable([UIApplication sharedApplication], "_statusBar", &result);

id status  = result;

for (id aview in [status subviews]) {

for (id bview in [aview subviews]) {

int batteryLevel = 0;

if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0){

object_getInstanceVariable(bview, "_capacity", &result);

batteryLevel = (int)result;

NSLog(@"电池电量:%d",batteryLevel);

if (batteryLevel > 0 && batteryLevel <= 100) {

return batteryLevel;

} else {

return 0;

}

}

}

}

return 0;

}

}

ARC:

- (int)getCurrentBatteryLevel

{

UIApplication *app = [UIApplication sharedApplication];

if (app.applicationState == UIApplicationStateActive||app.applicationState==UIApplicationStateInactive) {

Ivar ivar=  class_getInstanceVariable([app class],"_statusBar");

id status  = object_getIvar(app, ivar);

for (id aview in [status subviews]) {

int batteryLevel = 0;

for (id bview in [aview subviews]) {

if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >=6.0){

Ivar ivar=  class_getInstanceVariable([bview class],"_capacity");

if(ivar){

batteryLevel = ((int (*)(id, Ivar))object_getIvar)(bview, ivar);

//这种方式也可以

/*ptrdiff_t offset = ivar_getOffset(ivar);

unsigned char *stuffBytes = (unsigned char *)(__bridge void *)bview;

batteryLevel = * ((int *)(stuffBytes + offset));*/

NSLog(@"电池电量:%d",batteryLevel);

if (batteryLevel > 0 && batteryLevel <= 100) {

return batteryLevel;

} else {

return 0;

}

}

}

}

}

}

return 0;

}

这个方法和上面的方法都只能获取到电池电量所占百分比,不能获取到实际的电池电量毫安时。

于是,我选择去外国网站Stack Overflow去找寻我想要的答案。从而有了以下两种能满足需求的方法。链接在这里:http://stackoverflow.com/questions/12346230/how-to-obtain-extensive-battery-info-in-ios

方法三:UIDeviceListener

这个代码类可以监控电池电量的变化,从而捕获到系统电量资源相关类的调用字典解析到相关的值。其代码设计是通过监控UIDevice currentDevice 的  BatteryState  和 BatteryLevel的值变化来用c++集合来截取系统iOClass调用CoreFoudation的API从而产生部分信息的变化,最终转化成字典对象得以解析。不涉及私有API调用。github地址:https://github.com/eldade/UIDeviceListener。

然而,经过我的测试调用,这个方法的遗憾之处就是,无法获取到iOS 10易以后的相关数据。

调试iOS10系统机器之前获得到的字典的数据结构如下:

{

AdapterDetails =     {

Amperage = 1000;

Description = "usb host";

FamilyCode = "-536854528";

PMUConfiguration = 1000;

Watts = 5;

};

AdapterInfo = 16384;

Amperage = 1000;

AppleRawCurrentCapacity = 1279;

AppleRawMaxCapacity = 1275;

AtCriticalLevel = 0;

AtWarnLevel = 0;

BatteryData =     {

BatterySerialNumber = REDACTED;

ChemID = 355;

CycleCount = 524;

DesignCapacity = 1420;

Flags = 640;

FullAvailableCapacity = 1325;

ManufactureDate = REDACTED;

MaxCapacity = 1273;

MfgData = REDACTED;

QmaxCell0 = 1350;

StateOfCharge = 100;

Voltage = 4194;

};

BatteryInstalled = 1;

BatteryKey = "0003-default";

BootBBCapacity = 52;

BootCapacityEstimate = 2;

BootVoltage = 3518;

CFBundleIdentifier = "com.apple.driver.AppleD1815PMU";

ChargerConfiguration = 990;

CurrentCapacity = 1275;

CycleCount = 524;

DesignCapacity = 1420;

ExternalChargeCapable = 1;

ExternalConnected = 1;

FullyCharged = 1;

IOClass = AppleD1815PMUPowerSource;

IOFunctionParent64000000 = <>;

IOGeneralInterest = "IOCommand is not serializable";

IOInterruptControllers =     (

IOInterruptController34000000,

IOInterruptController34000000,

IOInterruptController34000000,

IOInterruptController34000000

);

IOInterruptSpecifiers =     (

<03000000>,

<26000000>,

<04000000>,

<24000000>

);

IOMatchCategory = AppleD1815PMUPowerSource;

IOPowerManagement =     {

CurrentPowerState = 2;

DevicePowerState = 2;

MaxPowerState = 2;

};

IOProbeScore = 0;

IOProviderClass = AppleD1815PMU;

InstantAmperage = 0;

IsCharging = 0;

Location = 0;

Manufacturer = A;

MaxCapacity = 1275;

Model = "0003-A";

Serial = REDACTED;

Temperature = 2590;

TimeRemaining = 0;

UpdateTime = 1461830702;

Voltage = 4182;

"battery-data" =     {

"0003-default" = <...>;

"0004-default" = <...>;

"0005-default" = <...};

"built-in" = 1;

}

方法四:EEIOKitListener

github地址:https://github.com/eldade/EEIOKitListener这个就可以实现iOS 8、9、10的电池信息获取,不过iOS10下获取数据比较少。这个方法的原理是通过私有API来获取IOKit.Framework中系统电池电量的相关类IOClass的属性AppleARMPMUCharger获取如下的结构。{

AdapterInfo = 16384;

AtCriticalLevel = 0;

CurrentCapacity = 1472;

ExternalChargeCapable = 1;

ExternalConnected = 1;

FullyCharged = 0;

IOClass = AppleARMPMUCharger;

IsCharging = 1;

MaxCapacity = 1600;

Voltage = 4281;

}

经过观察数据变化发现,这个类中发出的消息通知,是根据电池的电量的变化以及电压变化而产生的。然后这个电池电量值的变化的幅度也是总电容量的百分之一。

所以,综上所述,从iOS 10 之后苹果再次增加了系统部分的安全性的管理,我们也无法通过各种黑科技获取到更加详细的信息。而且,即使获取到了上述的数值,也不能达到更精准的值。当然,可能有更好的,更强大的方法,获取到更精准的值,只是我暂时没有找到,如果你有更好的方案,望不吝赐教。

你可能感兴趣的:(iOS 获取电池电量技术调研总结)