擷取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 = truelet batteryLevel = UIDevice.currentDevice().batteryLevelUIDevice.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
當然, 前提仍然是要把batteryMonitoringEnabled置為true。
最後,就可以查看並分析該APP的耗電量情況了。