11,电池级别和电池状态监听通知 2[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 3 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryStateDidChangeNotification object:nil]; 4 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; 5 62,电池的四种状态: 7NSArray *stateArray = [NSArray arrayWithObjects: @"Battery state is Unknown", @"Battery is not plugged into a charging source", @"Battery is charging", @"Battery state is full", nil]; 8 9 3,[[UIDevice currentDevice] batteryLevel] * 100];//电池的级别,一般都是0.0--1.0之间; 10 11[[UIDevice currentDevice] batteryState];//电池的状态 12 13完整代码: 14 15- (void) doLog: (NSString *) formatstring, ... 16{ 17 va_list arglist; 18 if (!formatstring) return; 19 va_start(arglist, formatstring); 20 NSString *outstring = [[[NSString alloc] initWithFormat:formatstring arguments:arglist] autorelease]; 21 va_end(arglist); 22 [self.log appendString:outstring]; 23 [self.log appendString:@"\n"]; 24 self.textView.text = self.log; 25} 26 27- (void) checkBattery: (id) sender 28{ 29 NSArray *stateArray = [NSArray arrayWithObjects: @"Battery state is Unknown", @"Battery is not plugged into a charging source", @"Battery is charging", @"Battery state is full", nil]; 30 self.log = [NSMutableString string]; 31 [self doLog:@"Battery level: %0.2f%", [[UIDevice currentDevice] batteryLevel] * 100]; 32 [self doLog:@"Battery state: %@", [stateArray objectAtIndex:[[UIDevice currentDevice] batteryState]]]; 33} 34 35- (void) viewDidLoad 36{ 37 self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR; 38 39 // Enable battery monitoring 40 [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 41 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryStateDidChangeNotification object:nil]; 42 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; 43 44 // Keep checking 45 [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(checkBattery:) userInfo:nil repeats:YES]; 46}
IOS中电池变化的监听
Wesley13
2021-10-11
1248 0 0
点赞
收藏
评论区
加载中...