码迷,mamicode.com
首页 > 移动开发 > 详细

获取IOS设备的电量信息:Battery Level

时间:2015-04-15 13:33:44      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:ios

本文介绍了如何通过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;
}

当然, 前提仍然是要把batteryMonitoringEnabled置为true。
最后,就可以查看并分析该APP的耗电量情况了。

获取IOS设备的电量信息:Battery Level

标签:ios

原文地址:http://blog.csdn.net/icetime17/article/details/45057721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!