- (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];
}
}
如何获取iPhone电池的状态和当前的电量
最新推荐文章于 2020-12-20 03:16:12 发布