iOS開發- 獲取精確剩余電量


[UIDevice currentDevice].batteryMonitoringEnabled = YES;
double deviceLevel = [UIDevice currentDevice].batteryLevel;


獲取當前剩余電量, 我們通常採用上述方法。

這也是蘋果官方文檔提供的。

它返回的是0.00-1.00之間的浮點值。

 另外, -1.00表示模擬器。

貌似這種方法不錯, 也非常easy。

可是細致觀察它的返回值, 我們能夠發現。 它是以0.05遞變的。 折算成100% 也就是以5%來遞變的。

也就是說, 這個辦法是存在缺陷的, 最起碼, 它不精確。


后來找到了一個方法。相當精確, 誤差保持在1%以內。

我們知道, Mac下有個IOKit.framework庫。

它能夠計算出我們須要的電量。

假設我們要使用它的話, (iOS是不提供的) 能夠先建立一個Mac下的project, 找到IOKit.framework。那IOKit.framework里面的IOPowerSources.hIOPSKeys.h復制到你的iOS項目中。

另外, 還須要把IOKit也導入到你的project中去。

(當然, 假設嫌麻煩, 能夠直接到我的Github中去下載project, 導出須要的文件)


先給出我的Github下載鏈接:https://github.com/colin1994/batteryLevelTest.git


以下詳細介紹下用法。


1。

導入須要的IOPowerSources.h, IOPSKeys.h 和 IOKit


2。

在實現的地方聲明頭文件

#import "IOPSKeys.h"
#import "IOPowerSources.h"

3。加入方法

/**
 *  Calculating the remaining energy
 *
 *  @return Current batterylevel
 */
-(double)getCurrentBatteryLevel
{
    
    //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 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 percent;
    }
    return -1.0f;
}


4。調用方法

NSLog(@"%.2f", [self getCurrentBatteryLevel]);





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM