IOS获取电池准确电量

找到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;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容