Detect battery warning was shown iPhone

六眼飞鱼酱① 提交于 2019-12-11 05:08:58

问题


Is there a way to detect whether a battery level warning was shown? I registered a notification to UIApplicationDidBecomeActiveNotification and I want to know whether it was triggered due to a low battery warning so I can handle it differently.


回答1:


You can monitor the battery level programmatically, and when it reaches a certain level, you can handle your event then.

-(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];
}


来源:https://stackoverflow.com/questions/5188505/detect-battery-warning-was-shown-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!