您的位置:首页 > 其它

如何获取iPhone电池的状态和当前的电量

2014-04-10 10:32 423 查看
- (void)batteryMoniter {
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    if (device.batteryState == UIDeviceBatteryStateUnknown) {
        NSLog(@"UnKnow");
    }else if (device.batteryState == UIDeviceBatteryStateUnplugged){
        NSLog(@"Unplugged");
    }else if (device.batteryState == UIDeviceBatteryStateCharging){
        NSLog(@"Charging");
    }else if (device.batteryState == UIDeviceBatteryStateFull){
        NSLog(@"Full");
    }   
    NSLog(@"%f",device.batteryLevel);
}

NSLog(@"%f",device.batteryLevel);//简单的这句就是了。

################################################

Having said that, I would not use a timer event for this, it is pretty inefficient. You want to use KVO instead:

- (void) viewWillAppear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = YES;
  currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  [device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];
  [super viewWillAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
  UIDevice *device = [UIDevice currentDevice];
  device.batteryMonitoringEnabled = NO;
  [device removeObserver:self forKeyPath:@"batteryLevel"];
  [super viewDidDisappear:animated];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  UIDevice *device = [UIDevice currentDevice];
  if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {
    currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: