如何从iphone中读取电池盒状态?

时间:2011-09-08 08:46:47

标签: iphone ios

  

可能重复:
  How to get battery status?

我正在实施一个iPhone应用程序,我希望通过编程来读取iPhone的电池状态。我不知道是否有可能。请给我建议。

2 个答案:

答案 0 :(得分:4)

要阅读电池电量和状态,您只需:

float battLvl = [[UIDevice currentDevice] batteryLevel]; // range is from 0.0 to 1.0
UIDeviceBatteryState battState = [UIDevice currentDevice] batteryStatus];

要监控电池电量和状态,您可以执行以下操作:

// enable monitoring and add observers with selector
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];

// Your notification handler
- (void)batteryChanged:(NSNotification *)notification
{
    UIDevice *device = [UIDevice currentDevice];
    NSLog(@"state: %i | charge: %f", device.batteryState, device.batteryLevel);
}

答案 1 :(得分:0)

以下代码行将有所帮助:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

[[UIDevice currentDevice] batteryLevel];
[[UIDevice currentDevice] batteryState];

有关详细信息,请参阅THIS链接。它会详细说明你。