iOS开发获取电池电量

原创 2015年11月17日 16:57:05

方法一:通过苹果官方文档里面UIDevice public API来获取,代码如下:

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
  [[NSNotificationCenter defaultCenter]
 addObserverForName:UIDeviceBatteryLevelDidChangeNotification
 object:nil queue:[NSOperationQueue mainQueue]
 usingBlock:^(NSNotification *notification) {
     // Level has changed
     NSLog(@"Battery Level Change");
     NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel);
 }];

但是经过测试发现,在iOS7 上 它是以0.05为单位的,但是在iOS9下测试,它是以0.01为单位的,虽然也是0.01为单位,但是测试多次也会出现偏差1%左右。也就是说, 这个办法是存在缺陷的, 最起码, 它不精确。

方法二:找到Mac下IOKit.framework,将IOKit.framework里面的IOPowerSources.h和IOPSKeys.h拷贝到你的iOS项目中。另外, 还需要把IOKit也导入到你的工程中去,此方法也会出现偏差,不精确。demo地址:batteryLevelTest

/** 
*  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;  
}

方法三:通过runtime 获取StatusBar上电池电量控件类私有变量的值,此方法可精准获取iOS6以上电池电量

MRC:
- (int)getCurrentBatteryLevel
{
 if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive||[UIApplication sharedApplication].applicationState==UIApplicationStateInactive) {
        void *result = nil;
        object_getInstanceVariable([UIApplication sharedApplication], "_statusBar", &result);
        id status  = result;
        for (id aview in [status subviews]) {
            for (id bview in [aview subviews]) {
                int batteryLevel = 0;
               if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
                {
                    object_getInstanceVariable(bview, "_capacity", &result);
                    batteryLevel = (int)result;
                    NSLog(@"电池电量:%d",batteryLevel);
                    if (batteryLevel > 0 && batteryLevel <= 100) {
                        return batteryLevel;

                    } else {
                        return 0;
                    }
                }

        }
    }

    return 0;
}

ARC:
- (int)getCurrentBatteryLevel
{

UIApplication *app = [UIApplication sharedApplication];
if (app.applicationState == UIApplicationStateActive||app.applicationState==UIApplicationStateInactive) {
    Ivar ivar=  class_getInstanceVariable([app class],"_statusBar");
    id status  = object_getIvar(app, ivar);
    for (id aview in [status subviews]) {
        int batteryLevel = 0;
        for (id bview in [aview subviews]) {
            if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >=6.0)
            {

                    Ivar ivar=  class_getInstanceVariable([bview class],"_capacity");
                    if(ivar)
                    {
                        batteryLevel = ((int (*)(id, Ivar))object_getIvar)(bview, ivar);
                        //这种方式也可以
                        /*ptrdiff_t offset = ivar_getOffset(ivar);
                         unsigned char *stuffBytes = (unsigned char *)(__bridge void *)bview;
                         batteryLevel = * ((int *)(stuffBytes + offset));*/
                        NSLog(@"电池电量:%d",batteryLevel);
                        if (batteryLevel > 0 && batteryLevel <= 100) {
                            return batteryLevel;

                        } else {
                            return 0;
                        }
                    }

            }

        }
    }
}
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

tencent GT ios测试电量

Temperature: 温度。 可以显示iphone运行时的电池温度,图中我的TOUCH4是36.9摄氏度,充电肯定比较热,平时是20多。 currentcapacity:电池当前容量。显示的是电池...

Tencent APT性能测试工具

APT是一个Android平台高效性能测试组件,提供丰富实用的功能,适用于开发自测、定位性能瓶颈;测试人员完成性能基准测试、竞品对比测试。

GT--记录android app消耗的cpu/内存/流量 /电量

腾讯GT简介: 此apk是一款可以对APP进行测试的软件,可以在任何情况下快速测试手机app的CPU、内存、流量、电量、帧率/流畅度等性能测试。有安卓版本和ios版本,分别下载 1.下载腾讯GT h...

手机发烫是为何—— App 电量测试定位方法

为什么要做电量测试 随着移动互联网的快速发展,手机的实用性、娱乐性越来越强。日常使用中发现,安装了应用后,即使不怎么使用,电量也会消耗很快。但如果恢复出场设置充满电后,手机可以待机很长时间。真相...

GT随身调 for ios

GT(随身调)是APP的随身调测平台,它是直接运行在手机上的“集成调测环境”(IDTE, Integrated Debug&Test Environment)。利用GT,仅凭一部手机,无需连接电脑,您...

ios性能测试-ios项目中集成GT

准备工作: 首先导入ios项目后,确保可以正常跑起来。再集成仅GT的framework。 点击项目文件中的xcworkspace,在xcode中打开。 导入证书,和.mobileprovision(双...

iOS 获取剩余电量

最简单的[UIDevice currentDevice].batteryMonitoringEnabled = YES; double deviceLevel = [UIDevice curren...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)