0

我想获得电池电量,并精确到 1%。我用谷歌搜索并找到了这个,

    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;

但这并不准确。所以我在这里寻求帮助。

4

1 回答 1

1

UIDevice类参考

您可以使用 UIDevice 实例获取有关电池充电状态(由 batteryState 属性描述)和充电水平(由 batteryLevel 属性描述)更改的信息和通知。

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float batteryLevel = [UIDevice currentDevice].batteryLevel;

NSLog(@"battery level: %f", batteryLevel * 100); 
于 2013-05-31T06:06:55.743 回答