如何准确获取iPhone的电池电量? [英] How to accurately obtain the iPhone battery level?

查看:137
本文介绍了如何准确获取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实例获取有关电池电量状态(由batteryState属性描述)和电量水平(由batteryLevel属性描述)的信息和通知.

You can use the UIDevice instance to obtain information and notifications about changes to the battery’s charge state (described by the batteryState property) and charge level (described by the batteryLevel property).

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆