如何获得电池状态?

时间:2008-12-01 10:30:00

标签: iphone cocoa-touch

如何在iPhone上获取电池状态?

5 个答案:

答案 0 :(得分:24)

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel];
int i=[myDevice batteryState];

int batinfo=(batLeft*100);

NSLog(@"Battry Level is :%d and Battery Status is :%d",batinfo,i);

switch (i)
{
    case UIDeviceBatteryStateUnplugged:
    {
        [BCStatus setText:NSLocalizedString(@"UnpluggedKey", @"")];
        break;
    }
    case UIDeviceBatteryStateCharging:
    {
        [BCStatus setText:NSLocalizedString(@"ChargingKey", @"")];
        break;
    }
    case UIDeviceBatteryStateFull:
    {
        [BCStatus setText:NSLocalizedString(@"FullKey", @"")];
        break;
    }
    default:
    {
        [BCStatus setText:NSLocalizedString(@"UnknownKey", @"")];
        break;
    }
}

BCStatus是uilabel。

答案 1 :(得分:3)

Iphone SDK 3.0 beta支持此功能。

答案 2 :(得分:2)

上面的答案非常好,但是它们都在Obj-C中,我已经将这些与其他示例一起用于MonoTouch上的相同任务,所以我将我的代码放在这里以防任何人需要它:

try
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
    _Battery.Level = (int)(UIDevice.CurrentDevice.BatteryLevel * IOSBatteryLevelScalingFactor);
    _Battery.State = UIDevice.CurrentDevice.BatteryState;
}
catch (Exception e)
{
    ExceptionHandler.HandleException(e, "BatteryState.Update");
    throw new BatteryUpdateException();
}
finally
{
    UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;
}

我的博客上也有完整的帖子,可以在here

中提供所有详细信息

答案 3 :(得分:0)

以下是我用作字符串作为快速实用方法的内容,请注意您必须启用电池监控才能获取值,然后如果您不想收到通知(显然可以获得一些效率,因为它们可以让你关闭它然后你应该在之后再次关闭它(就像我在这个功能中那样):

NSString *statusString(void)
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *batteryStateString = nil;
    switch(device.batteryState)
    {
        case UIDeviceBatteryStateUnplugged: batteryStateString = @"Unplugged"; break;
        case UIDeviceBatteryStateCharging: batteryStateString = @"Charging"; break;
        case UIDeviceBatteryStateFull: batteryStateString = @"Full"; break;
        default: batteryStateString = @"Unknown"; break;
    }

    [device setBatteryMonitoringEnabled:YES];
    NSString *statusString = [NSString stringWithFormat:@"Battery Level - %d%%, Battery State - %@",
                              (int)round(device.batteryLevel * 100), batteryStateString];
    [device setBatteryMonitoringEnabled:NO];
    return statusString;
}

答案 4 :(得分:-2)

现在3.1 SDK已发布,请在UIDevice文档中查找获取设备电池状态部分。这是电池*属性的早期。