您的位置:首页 > 移动开发 > IOS开发

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

2016-02-15 15:22 531 查看
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
double deviceLevel = [UIDevice currentDevice].batteryLevel;


获取当前剩余电量, 我们通常採用上述方法。

这也是苹果官方文档提供的。

它返回的是0.00-1.00之间的浮点值。

另外, -1.00表示模拟器。

貌似这种方法不错, 也非常easy。

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



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

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

我们知道, Mac下有个IOKit.framework库。

它能够计算出我们须要的电量。

假设我们要使用它的话, (iOS是不提供的) 能够先建立一个Mac下的project, 找到IOKit.framework。那IOKit.framework里面的IOPowerSources.hIOPSKeys.h复制到你的iOS项目中。

另外, 还须要把IOKit也导入到你的project中去。

(当然, 假设嫌麻烦, 能够直接到我的Github中去下载project, 导出须要的文件)

先给出我的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]);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: