行動裝置的耗電量向來是使用者最在意的指標之一,App 開發過程中難免需要收集運行期間的電量資訊,這也是衡量效能的重要依據。本文整理三種取得電量資料的途徑。
開始之前,請先確認 iPhone 設定中的電量統計已開啟。
Xcode 自帶的 Energy Diagnostics 工具可以記錄 iPhone 在特定時段的耗電情況。操作流程大致是:在 Developer 选项中選擇 Start Logging → 中斷 iPhone 與電腦的連接 → 進行一連串使用者操作 → Stop Logging → 重新連接並把資料匯入 Instruments。
這種方式取得的是整體能耗趨勢,適合效能除錯,但數值並不夠直觀,無法即時讀給程式邏輯使用。
UIDevice 提供了當前裝置的詳細資訊,例如 name、systemVersion、localizedModel、batteryLevel 等,是最簡便的做法。
UIDevice.currentDevice.batteryMonitoringEnabled = true let batteryLevel = UIDevice.currentDevice().batteryLevel UIDevice.currentDevice.batteryMonitoringEnabled = false
使用上有個關鍵前提:必須先把 batteryMonitoringEnabled 設為 true,否則讀到的值會固定是 -1。另外,iOS 8.0 之前 batteryLevel 只能精確到 5%,若需要 1% 精度就必須換用其他方式;iOS 8.0 之後才開始支援 1% 的精確度。
IOKit 是 iOS 中與硬體及核心服務溝通的 framework,常用於讀取硬體細節資訊。
首先把 IOPowerSources.h、IOPSKeys.h 與 IOKit 三個檔案導入專案,然後即可用下面的程式碼取得 1% 精度的電量:
-(double)getBatteryLevel {
// 取得一份包含電源來源資訊的不透明 CFTypeRef
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
// 取得電源來源清單,每個元素都是 CFTypeRef
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
int numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) {
NSLog(@"Error in CFArrayGetCount");
return -1.0f;
}
double currentCapacity = 0;
double maxCapacity = 0;
for (int i = 0; i < numOfSources; i++) {
psValue = (CFStringRef)CFArrayGetValueAtIndex(sources, i);
pSource = IOPSGetPowerSourceDescription(blob, psValue);
if (pSource) {
// 取得剩餘電量與總電量的資訊
currentCapacity = [[(__bridge NSString *)CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey))] doubleValue];
maxCapacity = [[(__bridge NSString *)CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey))] doubleValue];
}
}
double percentage = (currentCapacity / maxCapacity) * 100.0;
return percentage;
}
同樣地,前提仍要把 batteryMonitoringEnabled 設為 true。
三種方式各有定位:Instruments 用於宏觀的效能分析,UIDevice 適合一般情境下的簡易讀取,IOKit 則是唯一能在舊系統上取得 1% 精度的手段。完成量測後,就能進一步分析並改善 App 的耗電表現。