美文网首页
IOS获取电池准确电量

IOS获取电池准确电量

作者: Bana | 来源:发表于2017-09-01 17:52 被阅读47次

    找到Mac下IOKit.framework,将IOKit.framework里面的IOPowerSources.h和IOPSKeys.h拷贝到你的iOS项目中。另外, 还需要把IOKit也导入到你的工程中去,此方法也会出现偏差,不精确。

    //获取电池能量
    -(double)getCurrentBatteryLevel
    
    {
    
    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 curCapacity;
    
    }
    
    return -1.0f;
    
    }
    

    相关文章

      网友评论

          本文标题:IOS获取电池准确电量

          本文链接:https://www.haomeiwen.com/subject/eiykjxtx.html