獲取IOS設備的電量信息:Battery Level
本文介紹了如何通過API獲取IOS設備的電量信息。
移動設備的電量消耗一直是一個大問題,APP開發中也不可避免地需要收集APP運行時的電量消耗信息,這也是APP性能的衡量標準之一。
首先需要打開iphone設置中的電量統計。
1.通過Instruments獲取
Instruments工具自帶的Energy Diagnostics工具可以獲取到iphone特定時段的電量消耗信息。具體步驟:
打開Developer選項中的Start Logging —> 斷開iphone與PC連接 —> 一系列的用戶操作 —> Stop Logging —> 連接iphone與PC, 將電量消耗數據導入Instruments。
但這種方式獲取的信息不是非常直觀。
2. 通過UIDevice獲取
UIDevice提供了當前ios設備的詳細信息,如name, systemVersion, localizedModel, batteryLevel等。
UIDevice.currentDevice.batteryMonitoringEnabled = true let batteryLevel = UIDevice.currentDevice().batteryLevel UIDevice.currentDevice.batteryMonitoringEnabled = false
IOS系統的電量可以通過UIDevice獲取到,但在IOS 8.0之前,UIDevice中的batteryLevel只能精確到5%,需要通過其他方式獲取1%精度的電量信息。而在IOS 8.0之后,開始支持1%的精確度。
3. 通過IOKit framework來獲取
IOKit framework在IOS中用來跟硬件或內核服務通信,常用于獲取硬件詳細信息。
首先,需要將IOPowerSources.h,IOPSKeys.h,IOKit三個文件導入到工程中。然后即可通過如下代碼獲取1%精確度的電量信息:
-(double) getBatteryLevel{
// 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 percentage;
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
percentage = ((double) curCapacity / (double) maxCapacity * 100.0f);
NSLog(@"curCapacity : %d / maxCapacity: %d , percentage: %.1f ", curCapacity, maxCapacity, percentage);
return percentage;
}
return -1.0f;
}</pre>
當然, 前提仍然是要把batteryMonitoringEnabled置為true。
最后,就可以查看并分析該APP的耗電量情況了。
來自:http://blog.csdn.net/icetime17?viewmode=contents