2008-12-01 97 views

回答

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。

3

Iphone SDK 3.0 beta支持此功能。

+0

所有细节,尽管该信息可能由NDA ... – 2009-04-01 11:50:00

+0

覆盖......然后再次,它可能已被苹果公司宣布在一个公共论坛上。 – 2009-04-01 15:38:33

-2

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

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