2008-12-01 143 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