擷取IOS裝置的電量資訊:Battery Level

來源:互聯網
上載者:User

擷取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的耗電量情況了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.