如何获取iPhone电池的状态和当前的电量
来源:互联网 发布:数据交换平台 中软 编辑:程序博客网 时间:2024/05/02 04:04
- (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]; }}