本文介绍了如何准确获取iPhone的电池电量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取电池电量,并且准确到1%.我用谷歌搜索并找到了这个

I want to get the battery level,and Accurate to 1%.I googled and find this,

    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;

但这是不准确的.所以我在这里寻求帮助.

but it's not accurate.So I am asking for help here.

推荐答案

来自 UIDevice类参考:

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

NSLog(@"battery level: %f", batteryLevel * 100);

这篇关于如何准确获取iPhone的电池电量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 12:20