iOS开发- 获取精确剩余电量

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
double deviceLevel = [UIDevice currentDevice].batteryLevel;


获取当前剩余电量, 我们通常采用上述方法。这也是苹果官方文档提供的。

它返回的是0.00-1.00之间的浮点值。  另外, -1.00表示模拟器。

貌似这个方法不错, 也很简单。

但是仔细观察它的返回值, 我们可以发现。 它是以0.05递变的。 折算成100% 也就是以5%来递变的。

也就是说, 这个办法是存在缺陷的, 最起码, 它不精确。


后来找到了一个方法。相当精确, 误差保持在1%以内。

我们知道, Mac下有个IOKit.framework库。 它可以计算出我们需要的电量。

如果我们要使用它的话, (iOS是不提供的) 可以先建立一个Mac下的工程, 找到IOKit.framework,那IOKit.framework里面的IOPowerSources.hIOPSKeys.h拷贝到你的iOS项目中。另外, 还需要把IOKit也导入到你的工程中去。

(当然, 如果嫌麻烦, 可以直接到我的Github中去下载工程, 导出需要的文件)


先给出我的Github下载链接:https://github.com/colin1994/batteryLevelTest.git


下面具体介绍下使用方法。


1。导入需要的IOPowerSources.h, IOPSKeys.h 和 IOKit


2。在实现的地方声明头文件

#import "IOPSKeys.h"
#import "IOPowerSources.h"

3。添加方法

/**
 *  Calculating the remaining energy
 *
 *  @return Current batterylevel
 */
-(double)getCurrentBatteryLevel
{
    
    //Returns a blob of Power Source information in an opaque CFTypeRef.
    CFTypeRef blob = IOPSCopyPowerSourcesInfo();
    
    //Returns a CFArray of Power Source handles, each of type CFTypeRef.
    CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
    
    CFDictionaryRef pSource = NULL;
    const void *psValue;
    
    //Returns the number of values currently in an array.
    int numOfSources = CFArrayGetCount(sources);
    
    //Error in CFArrayGetCount
    if (numOfSources == 0)
    {
        NSLog(@"Error in CFArrayGetCount");
        return -1.0f;
    }
    
    //Calculating the remaining energy
    for (int i = 0 ; i < numOfSources ; i++)
    {
        //Returns a CFDictionary with readable information about the specific power source.
        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。调用方法

NSLog(@"%.2f", [self getCurrentBatteryLevel]);




iOS开发- 获取精确剩余电量,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。