1. 程式人生 > >如何獲取iPhone電池的狀態和當前的電量

如何獲取iPhone電池的狀態和當前的電量

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