首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检测电池警告显示为iPhone

检测电池警告显示为iPhone
EN

Stack Overflow用户
提问于 2011-03-04 08:58:27
回答 1查看 690关注 0票数 1

有没有办法检测是否显示了电池电量警告?我向UIApplicationDidBecomeActiveNotification注册了一个通知,我想知道它是否是由于电池电量不足而触发的,这样我就可以用不同的方式处理它。

EN

回答 1

Stack Overflow用户

发布于 2011-03-04 09:16:10

您可以通过编程方式监视电池电量,当电池电量达到一定水平时,您可以处理事件。

代码语言:javascript
复制
-(NSString*)batteryStateStatus:(UIDeviceBatteryState)state{
    switch ( state )
    {
        case UIDeviceBatteryStateUnknown:
            return @"Unknown";
            break;
        case UIDeviceBatteryStateUnplugged:
            return @"Unplugged";
            break;
        case UIDeviceBatteryStateCharging:
            return @"Charging";
        case UIDeviceBatteryStateFull:
            return @"Charged";
    }

    return nil;
}

-(NSString *)getBatteryPercent
{
    CFTypeRef blob = IOPSCopyPowerSourcesInfo();
    CFArrayRef sources = IOPSCopyPowerSourcesList(blob);

    CFDictionaryRef pSource = NULL;
    const void *psValue;

    NSString *thePercent;

    int i;
    int curCapacity = 0;
    int maxCapacity = 0;
    int percent;

    int numOfSources = CFArrayGetCount(sources);
    //if (numOfSources == 0) return 1;

    for (i = 0 ; i < numOfSources ; i++)
    {
        pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
        //if (!pSource) return 2;

        psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

        psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
        CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

        psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
        CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

        percent = (int)((double)curCapacity/(double)maxCapacity * 100);
    }

    return [NSString stringWithFormat:@"%d",percent];
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5188505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档