如何在插入电脑时监控iPhone的充电状态?

时间:2011-01-26 01:44:56

标签: iphone

我正在制作一个程序,可以在插入电脑时监控iPhone的充电状态。如何在VB,BAT或C ++中执行此操作?

1 个答案:

答案 0 :(得分:2)

您可以在计时器上设置以下内容(在ObjC中):

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

    CFDictionaryRef pSource = NULL;
    const void *psValue;

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

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

    for (i = 0 ; i < numOfSources ; i++)
    {
        pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));

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

获取电池的状态

-(NSString*)batteryStateStatus:(UIDeviceBatteryState)state
{
    switch ( state )
    {
        case UIDeviceBatteryStateUnknown:
            return @"Unknown";
            break;
        case UIDeviceBatteryStateUnplugged:
            return @"Unplugged";
            break;
        case UIDeviceBatteryStateCharging:
            return @"Charging";
            break;
        case UIDeviceBatteryStateFull:
            return @"Charged";
            break;
    }

    return nil;
}

编辑:

需要IOKit.framework

#include <IOKit/IOKitLib.h>
#include <IOKit/ps/IOPowerSources.h>
#include <IOKit/ps/IOPSKeys.h>