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.h和IOPSKeys.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]);
相关文章推荐
- IOS 开发 证书显示 此证书签发者无效 解决办法
- 打包生成IPA包时遇到错误:missing ios distribution signing identity for XXXXXXXXXX
- 关于IOS开发证书显示“此证书的签发者无效”解决方法
- iOS可执行文件瘦身方法
- 2016苹果开发者证书无效,怎么办
- iOS8以iOS8以下的系统present一个半透明的ViewController的方法
- iOS 整型转换警告"NSInteger' should not be used as format arguments; add an explicit cast to 'long' inste"
- ios开发证书变成证 “此证书的签发者无效了”
- iOS 7中自动布局教程
- iOS-关闭应用时想让应用直接退出的方法
- IOS开发证书显示“此证书的签发者无效”解决方法
- IOS开发证书显示“此证书的签发者无效”解决方法
- IOS开发证书变成“此证书的签发者无效”解决方法
- iOS 设置label的边距
- ios-此证书的签发者无效
- iOS开发证书变成“此证书的签发者无效”解决方法
- iOS IM开发准备工作(二)protobuf-objc安装及使用
- iOS中Block总结
- IOS开发证书变成“此证书的签发者无效”解决方法
- 002、iOS开发-NSLog不打印设置