我想获得电池电量,并且精确到1%。
我用Google搜索并找到了这个,
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
int numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) {
NSLog(@"Error in CFArrayGetCount");
return -1.0f;
}
for (int i = 0 ; i < numOfSources ; i++)
{
pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
if (!pSource) {
NSLog(@"Error in IOPSGetPowerSourceDescription");
return -1.0f;
}
psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));
int curCapacity = 0;
int maxCapacity = 0;
double percent;
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
percent = ((double)curCapacity/(double)maxCapacity * 100.0f);
return percent;
}
return -1.0f;
但这是不准确的。
所以我在这里寻求帮助。
最佳答案
从UIDevice
Class Reference:
您可以使用UIDevice实例获取有关电池电量状态(由batteryState属性描述)和电量水平(由batteryLevel属性描述)的信息和通知。
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float batteryLevel = [UIDevice currentDevice].batteryLevel;
NSLog(@"battery level: %f", batteryLevel * 100);
关于ios - 如何准确获取iPhone的电池电量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16850480/